Coding Questions Questions

Question Bank › Technical › C++ › Coding Questions

12

Classes and Objects

Q1.Easy
Write a C++ program that defines a class named Employee with two data members: an integer empId and a string empName. In main(), create one Employee object, assign empId = 305 and empName = "Rohan Mehta", then print both values on separate lines.
Show answer & explanation
Answer:
#include <iostream>
#include <string>
using namespace std;

class Employee {
public:
    int empId;
    string empName;
};

int main() {
    Employee e1;
    e1.empId = 305;
    e1.empName = "Rohan Mehta";
    cout << e1.empId << endl;
    cout << e1.empName << endl;
    return 0;
}
Explanation: 1) Include <iostream> and <string> for output and string support. 2) Define class Employee with public members empId (int) and empName (string). 3) In main(), declare an object e1 of type Employee. 4) Assign e1.empId = 305 and e1.empName = "Rohan Mehta". 5) Print empId then empName, each followed by endl, and return 0.
Q2.Easy
Write a C++ program that defines a class named Learner with data members: an integer rollNo and a string fullName. Add a member function assign(int r, string n) to set the values and a member function print() to display them separated by two spaces. In main, create two Learner objects, assign the first (411, "Anjali") and the second (412, "Vikram"), then call print() on both.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
class Learner {
   public:
       int rollNo;
       string fullName;
       void assign(int r, string n)
        {
            rollNo = r;
            fullName = n;
        }
       void print()
        {
            cout<<rollNo<<"  "<<fullName<<endl;
        }
};
int main(void) {
    Learner l1;
    Learner l2;
    l1.assign(411, "Anjali");
    l2.assign(412, "Vikram");
    l1.print();
    l2.print();
    return 0;
}
Explanation: 1) Class Learner has two data members, rollNo and fullName, so each object stores its own values. 2) assign() sets the members from its parameters; print() outputs rollNo, two spaces, then fullName. 3) main creates l1 and l2, then assigns 411/"Anjali" to l1 and 412/"Vikram" to l2. 4) l1.print() outputs 411 Anjali and l2.print() outputs 412 Vikram.
Q3.Easy
Write a C++ program that defines a class named Worker with data members: an integer empCode, a string empName and a float monthlyPay. Add a member function setDetails(int c, string n, float p) to assign these values and a member function showDetails() to print them separated by two spaces on one line. In main, create two Worker objects, set the first to (305, "Ramesh", 75000) and the second to (306, "Kavita", 42000), then call showDetails() on both.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
class Worker {
   public:
       int empCode;
       string empName;
       float monthlyPay;
       void setDetails(int c, string n, float p)
        {
            empCode = c;
            empName = n;
            monthlyPay = p;
        }
       void showDetails()
        {
            cout<<empCode<<"  "<<empName<<"  "<<monthlyPay<<endl;
        }
};
int main(void) {
    Worker w1;
    Worker w2;
    w1.setDetails(305, "Ramesh", 75000);
    w2.setDetails(306, "Kavita", 42000);
    w1.showDetails();
    w2.showDetails();
    return 0;
}
Explanation: 1) The class Worker declares three data members (empCode, empName, monthlyPay) that every object gets its own copy of. 2) setDetails() copies the arguments into the object's members; showDetails() prints them with two spaces between fields. 3) In main, two objects w1 and w2 are created; each call to setDetails() fills that object's own members. 4) w1.showDetails() prints 305 Ramesh 75000 and w2.showDetails() prints 306 Kavita 42000.

Dynamic Programming

Q4.Medium
Write a C++ program for the Ladder Climbing Problem. Problem Statement: “Given a ladder with n rungs, count how many possible ways there are to reach the top of the ladder, given that at every move you can either climb 1 rung, 2 rungs, or 3 rungs.” For example, for n = 4 the answer is 7.
Show answer & explanation
Answer:
#include <iostream>
#include <vector>
using namespace std;

class Ladder {
public:
    int CountWays(int n) {
        vector<int> dp(n + 1, 0);
        return CountWaysRecursive(dp, n);
    }
    int CountWaysRecursive(vector<int> &dp, int n) {
        if (n == 0) return 1;
        if (n == 1) return 1;
        if (n == 2) return 2;
        if (dp[n] == 0) {
            int take1 = CountWaysRecursive(dp, n - 1);
            int take2 = CountWaysRecursive(dp, n - 2);
            int take3 = CountWaysRecursive(dp, n - 3);
            dp[n] = take1 + take2 + take3;
        }
        return dp[n];
    }
};

int main() {
    Ladder *ld = new Ladder();
    cout << ld->CountWays(4) << endl;
    cout << ld->CountWays(5) << endl;
    cout << ld->CountWays(6) << endl;
    delete ld;
    return 0;
}
Explanation: 1) Base cases: 0 rungs -> 1 way (do nothing), 1 rung -> 1 way, 2 rungs -> 2 ways (1+1 or 2). 2) For n rungs, the last move was 1, 2, or 3 rungs, so ways(n) = ways(n-1)+ways(n-2)+ways(n-3). 3) dp[] memoizes results so each n is computed once. 4) ways(3)=1+2+1=4, ways(4)=2+1+4=7, ways(5)=4+2+7=13, ways(6)=7+4+13=24. 5) main prints 7, 13, 24.
Q5.Medium
Write a C++ program to solve the coin change problem: given a set of coin denominations and a target amount in rupees, find the minimum number of coins needed to make that amount. If it is not possible, print -1. For example, with denominations {1, 2, 5} and target 11, the minimum number of coins is 3 (5 + 5 + 1).
Show answer & explanation
Answer:
#include <iostream>
#include <vector>
#include <climits>
using namespace std;

int main() {
    vector<int> coins = {1, 2, 5};
    int amount = 11;
    vector<int> dp(amount + 1, INT_MAX);
    dp[0] = 0;
    for (int i = 1; i <= amount; i++) {
        for (int c : coins) {
            if (c <= i && dp[i - c] != INT_MAX) {
                dp[i] = min(dp[i], dp[i - c] + 1);
            }
        }
    }
    if (dp[amount] == INT_MAX)
        cout << -1 << endl;
    else
        cout << dp[amount] << endl;
    return 0;
}
Explanation: 1) Create a dp array of size amount+1 where dp[i] = minimum coins to make amount i, initialized to INT_MAX and dp[0]=0. 2) For each amount i from 1 to amount, try every coin c: if c<=i and dp[i-c] is reachable, update dp[i] = min(dp[i], dp[i-c]+1). 3) After filling, dp[amount] holds the minimum coin count; if it is still INT_MAX, the amount cannot be formed, so print -1. 4) For coins {1,2,5} and amount 11, dp[11] = 3 (5+5+1), so the program prints 3.
Q6.Medium
Write a C++ program to count the number of palindromic substrings in a given string. A palindrome reads the same forwards and backwards. For example, in the string "madam", the palindromic substrings are: "m", "a", "d", "a", "m", "ada", "madam" — total 7. Your program should read a string from the user and output the count.
Show answer & explanation
Answer:
#include <iostream>
#include <string>
using namespace std;

int countPalindromicSubstrings(string s) {
    int n = s.length();
    if (n == 0) return 0;
    bool dp[n][n];
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            dp[i][j] = false;
    int count = 0;
    // length 1
    for (int i = 0; i < n; i++) {
        dp[i][i] = true;
        count++;
    }
    // length 2
    for (int i = 0; i < n - 1; i++) {
        if (s[i] == s[i+1]) {
            dp[i][i+1] = true;
            count++;
        }
    }
    // length >=3
    for (int len = 3; len <= n; len++) {
        for (int i = 0; i <= n - len; i++) {
            int j = i + len - 1;
            if (s[i] == s[j] && dp[i+1][j-1]) {
                dp[i][j] = true;
                count++;
            }
        }
    }
    return count;
}

int main() {
    string str;
    cout << "Enter a string: ";
    cin >> str;
    int result = countPalindromicSubstrings(str);
    cout << "Number of palindromic substrings: " << result << endl;
    return 0;
}
Explanation: 1. Read the input string. 2. Create a 2D boolean table dp where dp[i][j] is true if substring from index i to j is a palindrome. 3. All single characters are palindromes: set dp[i][i] = true and increment count. 4. For length 2, if s[i] == s[i+1], set dp[i][i+1] = true and increment count. 5. For lengths 3 to n, for each start i, let j = i+len-1. If s[i] == s[j] and dp[i+1][j-1] is true, then dp[i][j] = true and increment count. 6. Finally, output the count.

References

Q7.Easy
Write a C++ program that demonstrates how a reference variable works as an alias for another variable. Declare an integer variable named 'num' and initialize it to 15. Then create a reference variable 'ref' that refers to 'num'. Print the value of 'num' using the reference variable 'ref'. Also, modify the value of 'num' through the reference to 25 and print the updated value of 'num' directly.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

int main() {
    int num = 15;          // original variable
    int &ref = num;        // reference variable (alias)
    cout << "Value of num using ref: " << ref << endl;
    ref = 25;              // modify num through reference
    cout << "Updated value of num: " << num << endl;
    return 0;
}
Explanation: 1. Declare an integer variable 'num' and initialize it to 15. 2. Declare a reference variable 'ref' of type int and bind it to 'num' using the syntax 'int &ref = num;'. Now 'ref' is another name for 'num'. 3. Output the value of 'num' using 'ref'. Since 'ref' refers to 'num', it prints 15. 4. Assign a new value 25 to 'ref'. This changes the value of 'num' because 'ref' is an alias. 5. Output the value of 'num' directly, which now shows 25.
Q8.Easy
Write a C++ program that declares an integer variable named 'marks' with the value 25, creates a reference named 'score' that refers to 'marks', and then prints the value of 'score' to the console.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main()
{
    int marks = 25;
    int &score = marks;
    std::cout << score << std::endl;
    return 0;
}
Explanation: Step 1: Include the iostream header so we can use std::cout. Step 2: In main, declare int marks = 25; this variable occupies a memory location. Step 3: Declare int &score = marks; the & makes 'score' a reference (an alias) to 'marks', so both names refer to the same memory. Step 4: Print score with std::cout; since score is an alias of marks, it outputs 25. Step 5: return 0 ends the program.
Q9.Easy
Write a C++ program that demonstrates that a reference must be initialized at the time of declaration. Declare an int variable x with value 25, create a reference y bound to x, and print the value of y.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

int main()
{
    int x = 25;      // variable initialization
    int &y = x;      // y is a reference to x, must be initialized here
    cout << "value of y is " << y << endl;
    return 0;
}
Explanation: 1) Include <iostream> for cout. 2) In main(), declare and initialize int x = 25. 3) Declare int &y = x; the reference y is bound to x at declaration (references cannot be left uninitialized). 4) Print y, which prints the value of x, i.e. 25. 5) Return 0.

Signal Handling

Q10.Medium
Write a C++ program that installs a signal handler for the SIGINT signal (Ctrl+C) using the signal() function. The handler should set a global flag of type sig_atomic_t to 1 when the signal is received. In main(), print "Waiting for signal..." and then loop until the flag becomes 1, after which print "Signal received, exiting." and return 0.
Show answer & explanation
Answer:
#include <iostream>
#include <csignal>

using namespace std;

volatile sig_atomic_t flag = 0;

void handleSignal(int sig)
{
    flag = 1;
}

int main()
{
    signal(SIGINT, handleSignal);
    cout << "Waiting for signal..." << endl;
    while (flag == 0)
    {
        // busy wait until signal arrives
    }
    cout << "Signal received, exiting." << endl;
    return 0;
}
Explanation: 1) Include <csignal> to use signal() and sig_atomic_t. 2) Declare a global sig_atomic_t flag initialized to 0. 3) Define handler handleSignal(int sig) that sets flag = 1. 4) In main(), call signal(SIGINT, handleSignal) to register the handler. 5) Print the waiting message, then loop while flag == 0. 6) When Ctrl+C is pressed, the handler runs, flag becomes 1, loop ends, and the exit message is printed.
Q11.Medium
Write a C++ program that demonstrates the use of the raise() function to send a SIGSEGV signal. The program should set up a signal handler for SIGSEGV that records the signal number in a global variable of type sig_atomic_t, then call raise(SIGSEGV), and finally print the recorded signal number.
Show answer & explanation
Answer:
#include <csignal>
#include <iostream>
using namespace std;

sig_atomic_t sig_val = 0;

void handler(int sig) {
    sig_val = sig;
}

int main() {
    signal(SIGSEGV, handler);
    raise(SIGSEGV);
    cout << "Signal number: " << sig_val << endl;
    return 0;
}
Explanation: 1. Include <csignal> for signal handling and <iostream> for output. 2. Declare a global variable sig_val of type sig_atomic_t to store the signal number. 3. Define a handler function that assigns the received signal number to sig_val. 4. In main(), register the handler for SIGSEGV using signal(). 5. Call raise(SIGSEGV) to send the SIGSEGV signal to the current process. 6. The handler executes and sets sig_val to SIGSEGV (typically 11). 7. Print the value of sig_val.
Q12.Medium
Write a C++ program that demonstrates the use of the raise() function to send a SIGFPE signal. The program should set up a signal handler for SIGFPE that records the signal number in a global variable of type sig_atomic_t, then call raise(SIGFPE), and finally print the recorded signal number.
Show answer & explanation
Answer:
#include <csignal>
#include <iostream>
using namespace std;

sig_atomic_t sig_val = 0;

void handler(int sig) {
    sig_val = sig;
}

int main() {
    signal(SIGFPE, handler);
    raise(SIGFPE);
    cout << "Signal number: " << sig_val << endl;
    return 0;
}
Explanation: 1. Include <csignal> for signal handling and <iostream> for output. 2. Declare a global variable sig_val of type sig_atomic_t to store the signal number. 3. Define a handler function that assigns the received signal number to sig_val. 4. In main(), register the handler for SIGFPE using signal(). 5. Call raise(SIGFPE) to send the SIGFPE signal to the current process. 6. The handler executes and sets sig_val to SIGFPE (typically 8). 7. Print the value of sig_val.

Signal Handling with raise()

Q13.Medium
Write a C++ program that demonstrates the use of the raise() function with the SIGABRT signal. The program should install a custom signal handler for SIGABRT using signal(), then call raise(SIGABRT). Inside the handler, store the received signal number in a global variable of type sig_atomic_t. After raise() returns, print the stored signal value to the console.
Show answer & explanation
Answer:
#include <iostream>
#include <csignal>

using namespace std;

sig_atomic_t caught_signal = 0;

void myHandler(int sig)
{
    caught_signal = sig;
}

int main()
{
    signal(SIGABRT, myHandler);
    raise(SIGABRT);
    cout << "Signal received: " << caught_signal << endl;
    return 0;
}
Explanation: 1. Include <csignal> for signal() and raise(), and <iostream> for output. 2. Declare a global variable caught_signal of type sig_atomic_t, initialized to 0, to safely store the signal number inside the handler. 3. Define myHandler(int sig) which simply assigns sig to caught_signal. 4. In main(), register myHandler for SIGABRT using signal(SIGABRT, myHandler). 5. Call raise(SIGABRT) to send the SIGABRT signal to the current process; the handler runs and sets caught_signal to the value of SIGABRT. 6. Print caught_signal, which shows the numeric value of SIGABRT (typically 6 on Linux).
Q14.Medium
Write a C++ program that installs a signal handler for SIGINT using signal(), then raises SIGINT with the raise() function. The handler should save the received signal number into a global variable of type sig_atomic_t, and main() should display that saved value after raising the signal.
Show answer & explanation
Answer:
#include <csignal>
#include <iostream>
using namespace std;

sig_atomic_t saved_signal = 0;

void catch_signal(int signum)
{
    saved_signal = signum;
}

int main()
{
    signal(SIGINT, catch_signal);
    raise(SIGINT);
    cout << "Caught signal: " << saved_signal << endl;
    return 0;
}
Explanation: 1. Include <csignal> for signal() and raise(), and <iostream> for printing. 2. Declare global sig_atomic_t saved_signal = 0; this type is safe to write inside a signal handler. 3. Define catch_signal(int signum) that assigns signum to saved_signal. 4. In main(), register the handler with signal(SIGINT, catch_signal). 5. Call raise(SIGINT) to deliver SIGINT to the process; the handler executes and records the signal number. 6. Print saved_signal, which shows the numeric value of SIGINT (typically 2).
Q15.Medium
Write a C++ program that installs a signal handler for SIGTERM using signal(), then raises SIGTERM with the raise() function. The handler should store the received signal number in a global variable of type sig_atomic_t, and main() should print the stored value after the signal is raised.
Show answer & explanation
Answer:
#include <csignal>
#include <iostream>
using namespace std;

sig_atomic_t stored_signal = 0;

void handler(int sig_num)
{
    stored_signal = sig_num;
}

int main()
{
    signal(SIGTERM, handler);
    raise(SIGTERM);
    cout << "Signal received: " << stored_signal << endl;
    return 0;
}
Explanation: 1. Include <csignal> for signal() and raise(), and <iostream> for output. 2. Declare a global sig_atomic_t variable stored_signal initialized to 0; sig_atomic_t is safe to modify inside a signal handler. 3. Define handler(int sig_num) which simply assigns sig_num to stored_signal. 4. In main(), call signal(SIGTERM, handler) to register the handler for SIGTERM. 5. Call raise(SIGTERM) to send SIGTERM to the current process; the handler runs and stores the signal number. 6. Print stored_signal, which shows the numeric value of SIGTERM (typically 15).

Other questions

Q16.Easy
Write a C++ program that opens a text file named "notes.txt" using ofstream, checks that the file opened successfully, writes two lines to it — "Welcome to Bharat Academy." and "C++ File Handling." — then closes the file. If the file cannot be opened, print "File opening failed."
Show answer & explanation
Answer:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
    ofstream filestream("notes.txt");
    if (filestream.is_open()) {
        filestream << "Welcome to Bharat Academy.\n";
        filestream << "C++ File Handling.\n";
        filestream.close();
    } else {
        cout << "File opening failed.";
    }
    return 0;
}
Explanation: 1. Include <fstream> which provides ofstream (output file stream) for creating and writing files. 2. Create an ofstream object bound to "notes.txt"; this creates/truncates the file. 3. Use is_open() to verify the file opened. 4. If open, write the two lines using the << operator, each ending with \n. 5. Call close() to flush and release the file. 6. If not open, print the failure message.
Q17.Easy
Write a C++ program that creates a std::string object initialized with the text "Namaste" and also creates a std::string from a character array containing the characters 'I','N','D'. Print both strings on separate lines.
Show answer & explanation
Answer:
#include <iostream>
#include <string>
using namespace std;
int main() {
    string s1 = "Namaste";
    char ch[] = {'I', 'N', 'D'};
    string s2(ch, 3);
    cout << s1 << endl;
    cout << s2 << endl;
    return 0;
}
Explanation: 1. Include <iostream> for cout and <string> for std::string. 2. Create string s1 initialized with "Namaste". 3. Create a char array ch = {'I','N','D'}. 4. Construct string s2 from the char array using string(ch); the array is treated as a C-string, so it reads characters until a null terminator (the compiler adds one after the three characters). 5. Print s1 and s2 each followed by endl, giving output: Namaste IND
Q18.Easy
Write a C++ program that defines a class named 'Student' with a default constructor (a constructor taking no arguments). The constructor should print "Default Constructor Called" when an object is created. In main(), create two objects of the class Student and return 0.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
class Student
{
  public:
       Student()
       {
           cout<<"Default Constructor Called"<<endl;
       }
};
int main(void)
{
    Student s1; // creating an object of Student
    Student s2;
    return 0;
}
Explanation: 1. Define class Student with a public constructor Student() that takes no arguments (a default constructor). 2. Inside the constructor, print "Default Constructor Called". 3. In main(), declare Student s1; — this automatically invokes the default constructor and prints the message. 4. Declare Student s2; — the constructor is invoked again, printing the message a second time. 5. The program ends with return 0; so the output is the message printed twice.
Q19.Easy
Write a C++ program that defines a class `Student` with data members `roll` (int), `name` (string) and `marks` (float). Provide a parameterized constructor to initialize these members, and a `display()` method that prints roll, name and marks separated by spaces. In `main`, create two objects: Student(11, "Aarav", 92.5) and Student(12, "Diya", 78.0), and call display() on both.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

class Student {
public:
    int roll;
    string name;
    float marks;
    Student(int r, string n, float m)
    {
        roll = r;
        name = n;
        marks = m;
    }
    void display()
    {
        cout << roll << "  " << name << "  " << marks << endl;
    }
};

int main()
{
    Student s1(11, "Aarav", 92.5);
    Student s2(12, "Diya", 78.0);
    s1.display();
    s2.display();
    return 0;
}
Explanation: 1. Define class Student with public data members roll, name and marks. 2. The parameterized constructor Student(int r, string n, float m) assigns the arguments to the members. 3. display() prints roll, name and marks separated by spaces. 4. In main, create s1 with (11, "Aarav", 92.5) and s2 with (12, "Diya", 78.0); the constructor runs for each object. 5. Calling s1.display() prints: 11 Aarav 92.5 6. Calling s2.display() prints: 12 Diya 78
Q20.Easy
Write a C++ program that defines a function template `showAll` which takes a pair of forward iterators (begin and end) and prints all the elements in the range separated by spaces, advancing the iterator with the increment operator. In `main`, create a `std::vector<int>` containing the values 15, 25, 35, 45, 55 and call `showAll` to display them.
Show answer & explanation
Answer:
#include <iostream>
#include <vector>
using namespace std;

template<class ForwardIterator>
void showAll(ForwardIterator first, ForwardIterator last)
{
    while(first != last)
    {
        cout << *first << " ";
        first++;
    }
    cout << endl;
}

int main()
{
    vector<int> nums = {15, 25, 35, 45, 55};
    showAll(nums.begin(), nums.end());
    return 0;
}
Explanation: 1. Include <iostream> and <vector> for output and the container. 2. Define a function template showAll that accepts two forward iterators first and last. 3. Inside the loop, dereference the iterator with *first to print the value, then increment it with first++ to move forward. 4. The loop stops when first equals last, so every element is printed exactly once. 5. In main, create a vector with 15, 25, 35, 45, 55 and pass begin() and end() to showAll. 6. Output: 15 25 35 45 55
Q21.Easy
Write a C++ program that reads a full line of text (which may contain spaces) from the user using the getline() function and then prints it. For example, if the user enters 'Hello World', the program should output 'Hello World'. Use the string class and the getline() function.
Show answer & explanation
Answer:
#include <iostream>
#include <string>
using namespace std;

int main() {
    string text;
    cout << "Enter a line of text: ";
    getline(cin, text);
    cout << "You entered: " << text << endl;
    return 0;
}
Explanation: 1. Include <iostream> for input/output and <string> for string class. 2. Declare a string variable text. 3. Prompt the user to enter a line of text. 4. Use getline(cin, text) to read the entire line including spaces. 5. Print the entered text using cout.
Q22.Easy
Write a C++ program that stores the numbers 10, 20, 30, 40, 50 in a vector. Create two iterators: one pointing to the first element and another pointing to the second element. Compare them using the equality (==) and inequality (!=) operators, and print "Iterators are equal" if they are equal, otherwise print "Iterators are not equal".
Show answer & explanation
Answer:
#include <iostream>
#include<vector>
#include<iterator>
using namespace std;
int main()
{
    vector<int> v{10,20,30,40,50};
    vector<int>::iterator itr,itr1;
    itr=v.begin();
    itr1=v.begin()+1;
    if(itr==itr1)
    std::cout << "Iterators are equal" << std::endl;
    if(itr!=itr1)
    std::cout << "Iterators are not equal" << std::endl;
    return 0;
}
Explanation: 1. Create a vector v with values 10,20,30,40,50. 2. Declare two iterators itr and itr1. 3. Set itr = v.begin() (points to 10) and itr1 = v.begin()+1 (points to 20). 4. Since they point to different locations, itr==itr1 is false, so the first if is skipped. 5. itr!=itr1 is true, so the program prints "Iterators are not equal".
Q23.Easy
Write a C++ program that defines a class named 'Student'. The class should have a constructor that prints "Student created" and a destructor that prints "Student destroyed". In main(), create two objects of the class. The constructor and destructor should be invoked automatically.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
class Student
{
  public:
        Student()
        {
            cout<<"Student created"<<endl;
        }
        ~Student()
        {
            cout<<"Student destroyed"<<endl;
        }
};
int main(void)
{
    Student s1;
    Student s2;
    return 0;
}
Explanation: 1. Define class Student with a public constructor Student() that prints "Student created". 2. Add a public destructor ~Student() that prints "Student destroyed". 3. In main(), declare two objects s1 and s2; each declaration automatically calls the constructor, so "Student created" prints twice. 4. When main() ends, destructors run automatically in reverse order of creation, so "Student destroyed" prints twice.
Q24.Easy
Write a C++ program that uses ostream_iterator to print the elements of a vector separated by commas. Create a vector of integers and fill it with the values 5, 10, 15, 20, 25 using a loop. Then use an ostream_iterator with cout and a comma as the delimiter to output all elements. Include necessary headers.
Show answer & explanation
Answer:
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> v;
    for (int i = 1; i <= 5; i++) {
        v.push_back(i * 5);
    }
    ostream_iterator<int> out(cout, ",");
    copy(v.begin(), v.end(), out);
    return 0;
}
Explanation: 1. Include the necessary headers: iostream, iterator, vector, and algorithm. 2. Create an empty vector<int> v. 3. Use a for loop from 1 to 5 to push back i*5, resulting in elements 5, 10, 15, 20, 25. 4. Create an ostream_iterator<int> named out that writes to cout with a comma delimiter. 5. Use the copy algorithm to copy all elements from v to out, which prints them separated by commas. 6. The output will be: 5,10,15,20,25,
Q25.Easy
Write a C++ program to demonstrate the use of the 'this' pointer to refer to instance variables. Create a class named 'Student' with data members: roll (int), name (string), and marks (float). The constructor should take parameters with the same names as the data members and use the 'this' pointer to assign them. Include a member function 'display()' that prints the roll, name, and marks of the student. In main(), create two Student objects: one with roll 201, name "Amit", marks 85.5; and another with roll 202, name "Priya", marks 92.0. Call display() for both objects.
Show answer & explanation
Answer:
#include <iostream>
#include <string>
using namespace std;

class Student {
public:
    int roll;
    string name;
    float marks;
    Student(int roll, string name, float marks) {
        this->roll = roll;
        this->name = name;
        this->marks = marks;
    }
    void display() {
        cout << roll << "  " << name << "  " << marks << endl;
    }
};

int main() {
    Student s1(201, "Amit", 85.5);
    Student s2(202, "Priya", 92.0);
    s1.display();
    s2.display();
    return 0;
}
Explanation: 1. Define a class Student with data members roll, name, and marks. 2. The constructor takes parameters with the same names as the data members. 3. Inside the constructor, use 'this->roll = roll;' etc., to assign the parameter values to the current object's members. 4. The display() function prints the student details. 5. In main(), create two Student objects with the given values and call display() for each.
Q26.Easy
Write a C++ program that defines a class named BankAccount with data members accNo (int) and holderName (string), and a static member interestRate (float) that is shared by all accounts. The constructor should take accNo and holderName and assign them. Include a display() method that prints accNo, holderName and the shared interestRate. In main(), set the static interestRate to 6.5, create two BankAccount objects and call display() on both.
Show answer & explanation
Answer:
#include <iostream>
#include <string>
using namespace std;

class BankAccount {
public:
    int accNo;
    string holderName;
    static float interestRate;

    BankAccount(int accNo, string holderName) {
        this->accNo = accNo;
        this->holderName = holderName;
    }

    void display() {
        cout << accNo << " " << holderName << " " << interestRate << endl;
    }
};

float BankAccount::interestRate = 0.0f;

int main() {
    BankAccount::interestRate = 6.5f;

    BankAccount a1(201, "Meera");
    BankAccount a2(202, "Rohan");

    a1.display();
    a2.display();
    return 0;
}
Explanation: 1. Declare class BankAccount with instance members accNo and holderName and a static float interestRate. 2. Define the static member outside the class: float BankAccount::interestRate = 0.0f; so only one shared copy exists. 3. The constructor assigns accNo and holderName using this->. 4. display() prints accNo, holderName and the shared interestRate. 5. In main(), set BankAccount::interestRate = 6.5f once; this value is visible to all objects. 6. Create two objects and call display() on each; both print the same interestRate 6.5.
Q27.Easy
Write a C++ program that defines a class named Student with data members rollNo (int) and studentName (string), and a static member count that keeps track of how many Student objects have been created. The constructor should take rollNo and studentName, assign them, and increment count. Include a display() method that prints rollNo and studentName. In main(), create three Student objects and print the total number of objects created using the static member.
Show answer & explanation
Answer:
#include <iostream>
#include <string>
using namespace std;

class Student {
public:
    int rollNo;
    string studentName;
    static int count;

    Student(int rollNo, string studentName) {
        this->rollNo = rollNo;
        this->studentName = studentName;
        count++;
    }

    void display() {
        cout << rollNo << " " << studentName << endl;
    }
};

int Student::count = 0;

int main() {
    Student s1(101, "Aarav");
    Student s2(102, "Diya");
    Student s3(103, "Kabir");

    s1.display();
    s2.display();
    s3.display();

    cout << "Total objects created: " << Student::count << endl;
    return 0;
}
Explanation: 1. Declare class Student with instance members rollNo and studentName and a static int count. 2. Define the static member outside the class: int Student::count = 0; so a single shared copy exists. 3. The constructor assigns rollNo and studentName using this-> and increments count each time an object is created. 4. display() prints the rollNo and studentName of the object. 5. In main(), three Student objects are created, so count becomes 3. 6. Student::count is printed, showing the total number of objects created.
Q28.Easy
Write a C++ program that defines a struct named 'Rectangle' with two integer data members: 'length' and 'breadth'. In the main function, declare a struct Rectangle variable, assign length = 10 and breadth = 4 using the dot operator, and then print the area of the rectangle.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

struct Rectangle {
    int length, breadth;
};

int main() {
    Rectangle rec;
    rec.length = 10;
    rec.breadth = 4;
    cout << "Area of Rectangle is: " << (rec.length * rec.breadth) << endl;
    return 0;
}
Explanation: 1. Define a struct 'Rectangle' with two integer members: length and breadth. 2. In main, declare a variable 'rec' of type Rectangle. 3. Assign rec.length = 10 and rec.breadth = 4 using the dot operator. 4. Compute area as rec.length * rec.breadth and print it with a message. 5. The output will be: Area of Rectangle is: 40.
Q29.Easy
Write a C++ program that defines a struct named 'Rectangle' with integer data members 'length' and 'breadth'. The struct should have a constructor that initializes these members, and a method 'calculateArea' that prints the area of the rectangle. In the main function, create a Rectangle object with length 7 and breadth 9, and call the method to display the area.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

struct Rectangle {
    int length, breadth;
    Rectangle(int l, int b) {
        length = l;
        breadth = b;
    }
    void calculateArea() {
        cout << "Area of Rectangle is: " << (length * breadth);
    }
};

int main() {
    Rectangle rec(7, 9);
    rec.calculateArea();
    return 0;
}
Explanation: 1. Define a struct 'Rectangle' with two integer members: length and breadth. 2. Add a constructor that takes two integers and assigns them to length and breadth. 3. Add a method 'calculateArea' that computes and prints length * breadth. 4. In main, create a Rectangle object 'rec' with arguments 7 and 9, which calls the constructor. 5. Call rec.calculateArea() to print the area (63).
Q30.Easy
Write a C++ program that demonstrates the enum data type. Define an enum named 'month' with the values January, February, March, April, May, June, July, August, September, October, November, December. In main, declare a variable of type month, assign it the value September, and print 'Month: ' followed by the value of the enum variable plus 1.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
enum month { January, February, March, April, May, June, July, August, September, October, November, December };
int main()
{
    month m;
    m = September;
    cout << "Month: " << m + 1 << endl;
    return 0;
}
Explanation: 1) The enum month lists 12 names; by default January=0, February=1, ... December=11. 2) September is the 9th name, so its underlying integer value is 8. 3) main assigns September to the variable m. 4) Printing m + 1 adds 1 to the integer value 8, giving 9. 5) Output: 'Month: 9'.
Q31.Easy
Write a C++ program that demonstrates a friend function. Create a class named 'Parcel' with a private integer member 'weight'. Give it a default constructor that sets weight to 0. Declare a friend function 'int addWeight(Parcel)' that adds 15 to the parcel's weight and returns the new weight. In main, create a Parcel object and print the result of addWeight in the form: Weight of parcel: <value>
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
class Parcel
{
    private:
        int weight;
    public:
        Parcel(): weight(0) { }
        friend int addWeight(Parcel); // friend function
};
int addWeight(Parcel p)
{
    p.weight += 15;
    return p.weight;
}
int main()
{
    Parcel p;
    cout << "Weight of parcel: " << addWeight(p) << endl;
    return 0;
}
Explanation: 1) The class Parcel keeps 'weight' private, so outside code cannot access it directly. 2) The line 'friend int addWeight(Parcel);' lets the free function addWeight read and modify Parcel's private members. 3) The default constructor sets weight to 0. 4) addWeight receives a Parcel by value, adds 15 to its weight (allowed because it is a friend) and returns the new weight. 5) main creates a Parcel and prints 'Weight of parcel: 15'.
Q32.Easy
Write a C++ program that demonstrates a friend class. Create a class `Wallet` with a private integer member `amount` initialised to 750. Declare class `Auditor` as a friend of `Wallet`. Class `Auditor` should have a public method `showBalance(Wallet &w)` that prints the private `amount` of the wallet. In `main`, create a `Wallet` object and an `Auditor` object and call `showBalance`.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
class Wallet
{
    int amount = 750;
    friend class Auditor;   // friend class
};
class Auditor
{
  public:
    void showBalance(Wallet &w)
    {
        cout << "balance is : " << w.amount;
    }
};
int main()
{
    Wallet w;
    Auditor a;
    a.showBalance(w);
    return 0;
}
Explanation: 1. `Wallet` keeps `amount` private (value 750). 2. The line `friend class Auditor;` inside `Wallet` gives `Auditor` access to all private members of `Wallet`. 3. `Auditor::showBalance` takes a `Wallet&` and directly reads `w.amount`, which is allowed because of the friendship. 4. In `main`, a `Wallet` and an `Auditor` are created and `showBalance(w)` is called. 5. Output: balance is : 750.
Q33.Easy
Write a C++ program that reads 6 integers into an array named scores, assigns the array name to an integer pointer p, and then prints the value of *p and the value of *scores.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main()
{
    int *p;
    int scores[6];
    cout << "Enter the elements of an array:" << endl;
    for(int i = 0; i < 6; i++)
    {
        cin >> scores[i];
    }
    p = scores;
    cout << "The value of *p is :" << *p << endl;
    cout << "The value of *scores is :" << *scores << endl;
    return 0;
}
Explanation: 1) Declare an integer pointer p and an integer array scores[6]. 2) Read 6 numbers into scores with a loop. 3) p = scores; the array name decays to the address of its first element, so p points to scores[0]. 4) *p dereferences p and gives scores[0]. 5) *scores also dereferences the array name, giving scores[0] again, so both printed values are the first entered number.
Q34.Easy
Write a C++ program that reads 4 integers into a normal integer array, stores the address of each element into an array of integer pointers, and then prints each value by dereferencing the pointers. Use the variable names numArr for the integer array and ptrArr for the array of pointers.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main()
{
    int numArr[4];
    int *ptrArr[4];
    cout << "Enter four numbers:" << endl;
    for(int i = 0; i < 4; i++)
    {
        cin >> numArr[i];
    }
    for(int i = 0; i < 4; i++)
    {
        ptrArr[i] = &numArr[i];
    }
    cout << "The values are" << endl;
    for(int i = 0; i < 4; i++)
    {
        cout << *ptrArr[i] << endl;
    }
    return 0;
}
Explanation: 1) Declare an integer array numArr[4] and an array of 4 integer pointers ptrArr[4]. 2) Read 4 numbers from the user into numArr using a loop. 3) In a second loop, set ptrArr[i] = &numArr[i], so each pointer holds the address of the matching array element. 4) In a third loop, print *ptrArr[i], which dereferences the pointer and gives back the stored value. 5) The output is the same 4 numbers, one per line.
Q35.Easy
Write a C++ program that declares an array of pointers to strings (character pointers) initialized with the names "Amit", "Priya", "Rahul", "Sneha", "Karan". The program should then print each name on a new line using the array of pointers.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main() {
    const char *names[5] = {"Amit", "Priya", "Rahul", "Sneha", "Karan"};
    for (int i = 0; i < 5; i++) {
        cout << names[i] << endl;
    }
    return 0;
}
Explanation: 1. Declare an array of 5 pointers to const char and initialize it with string literals. 2. Each element of the array holds the address of the first character of the corresponding string. 3. Use a for loop to iterate over the array indices 0 to 4. 4. Inside the loop, print names[i] which outputs the string pointed to. 5. The program prints each name on a separate line.
Q36.Easy
Write a C++ program that creates a single-dimensional integer array of size 6, initializes it with the values 5, 0, 15, 0, 25, 0, and then traverses the array to print each element on a new line.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main() {
    int arr[6] = {5, 0, 15, 0, 25, 0};
    for (int i = 0; i < 6; i++) {
        cout << arr[i] << "\n";
    }
    return 0;
}
Explanation: 1. Declare an integer array of size 6 and initialize it with the given values. 2. Use a for loop with index i from 0 to 5 to access each element. 3. Inside the loop, print arr[i] followed by a newline. 4. The program outputs each element on a separate line.
Q37.Easy
Write a C++ program that creates an integer array with the values {4, 0, 7, 0, 9} and traverses it using a range-based for (foreach) loop, printing each element on its own line.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main()
{
    int arr[5] = {4, 0, 7, 0, 9};
    for (int i : arr)
    {
        cout << i << "\n";
    }
    return 0;
}
Explanation: 1) Declare and initialise int arr[5] = {4, 0, 7, 0, 9}. 2) Use a range-based for loop: 'for (int i : arr)' copies each element into i in order. 3) Inside the loop print i followed by a newline. 4) Output is 4, 0, 7, 0, 9 each on a separate line.
Q38.Easy
Write a C++ program that stores the marks of 5 students in an array, prints each mark, then computes and displays the total sum and the average of the marks. Use the marks {23, 15, 18, 12, 32}.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main() {
    int marks[] = {23, 15, 18, 12, 32};
    int sum = 0;
    int count = 0;
    cout << "The marks are: ";
    for (int m : marks) {
        cout << m << "  ";
        sum += m;
        ++count;
    }
    cout << "\nTheir Sum = " << sum << endl;
    double average = (double)sum / count;
    cout << "Their Average = " << average << endl;
    return 0;
}
Explanation: 1) Declare an int array marks with the 5 given values. 2) Initialise sum = 0 and count = 0. 3) Use a range-based for loop over marks: print each mark, add it to sum, and increment count. 4) Sum = 23+15+18+12+32 = 100, count = 5. 5) Average = 100 / 5 = 20 (cast to double for a clean result). 6) Print the sum and the average.
Q39.Easy
Write a C++ program that stores the marks {12, 9, 15, 4, 21} in an integer array of size 5 and prints all the elements twice: first using a range-based for loop and then using a traditional index-based for loop, with the label "The marks are: " before each set.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main() {
    int marks[5] = {12, 9, 15, 4, 21};
    cout << "The marks are: ";
    for (const int &m : marks) {
        cout << m << "  ";
    }
    cout << "\nThe marks are: ";
    for (int i = 0; i < 5; ++i) {
        cout << marks[i] << "  ";
    }
    return 0;
}
Explanation: 1. An integer array marks of size 5 is initialised with 12, 9, 15, 4, 21. 2. The first cout prints the label "The marks are: ". 3. The range-based for loop (const int &m : marks) visits each element in order and prints it followed by two spaces. 4. A newline and the label are printed again. 5. The traditional for loop runs i from 0 to 4 and prints marks[i] with two spaces, giving the same sequence twice.
Q40.Easy
Write a C++ program that uses a for loop to print the numbers 1 to 10, but stops (breaks out of the loop) as soon as the number 7 is reached, so that 7 and later numbers are not printed.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main() {
    for (int i = 1; i <= 10; i++) {
        if (i == 7) {
            break;
        }
        cout << i << "\n";
    }
    return 0;
}
Explanation: 1. The for loop starts i at 1 and runs while i <= 10, incrementing i each time. 2. Inside the loop, the if condition checks whether i equals 7. 3. When i becomes 7, the break statement immediately exits the loop, so control jumps past the loop body. 4. For i = 1 to 6 the condition is false, so cout prints each value on its own line. 5. Output is 1,2,3,4,5,6 each on a new line; 7 and beyond are never printed.
Q41.Easy
Write a C++ program that uses the standard output stream (cout) to display a welcome message. The program should declare a character array initialized with the string "Welcome to C++ tutorial" and then print it to the console using cout. The output should be: "Value of ary is: Welcome to C++ tutorial".
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

int main() {
    char ary[] = "Welcome to C++ tutorial";
    cout << "Value of ary is: " << ary << endl;
    return 0;
}
Explanation: 1. Include the <iostream> header to use cout. 2. Use the std namespace to avoid writing std::cout. 3. In main(), declare a character array ary and initialize it with the string "Welcome to C++ tutorial". 4. Use cout with the insertion operator (<<) to print the text "Value of ary is: " followed by the contents of ary and then endl to insert a newline. 5. Return 0 to indicate successful execution.
Q42.Easy
Write a C++ program that asks the user to enter their roll number (an integer) using cin, then prints the message "Your roll number is: " followed by the entered number. For example, if the user enters 17, the output should be: Your roll number is: 17
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main() {
    int roll;
    cout << "Enter your roll number: ";
    cin >> roll;
    cout << "Your roll number is: " << roll << endl;
    return 0;
}
Explanation: 1. Include <iostream> to use cin and cout. 2. Declare an integer variable 'roll' to store the input. 3. Print a prompt "Enter your roll number: " using cout. 4. Read the integer from the keyboard with cin >> roll (the extraction operator >> stores the typed value in roll). 5. Print "Your roll number is: " followed by the value of roll and endl. 6. If the user types 17, the output is: Your roll number is: 17
Q43.Easy
Write a C++ program that prints three lines using the endl manipulator: first line should be "Welcome to C++", second line "Learning is fun", and third line "End of output". Each line must be terminated with endl.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main() {
    cout << "Welcome to C++" << endl;
    cout << "Learning is fun" << endl;
    cout << "End of output" << endl;
    return 0;
}
Explanation: 1. Include the <iostream> header so cout and endl are available. 2. Use 'using namespace std;' so we can write cout and endl without the std:: prefix. 3. In main, use cout with the << operator to print each string. 4. Append endl after each string: endl inserts a newline character and flushes the output stream. 5. The program prints three separate lines in order and returns 0.
Q44.Easy
Write a C++ program that prints 'Hello, India!' to the console. The program should include the necessary header and use the standard namespace. What is the correct program?
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

int main() {
    cout << "Hello, India!" << endl;
    return 0;
}
Explanation: 1. Include the iostream header for input/output operations. 2. Use 'using namespace std;' to avoid writing std:: before cout and endl. 3. Define the main function with return type int. 4. Inside main, use cout to print the string "Hello, India!" followed by endl to insert a newline. 5. Return 0 to indicate successful execution.
Q45.Easy
Write a C++ program to demonstrate call by value. Create a function named 'modify' that takes an integer parameter by value and changes it to 100. In main(), declare an integer variable 'num' initialized to 7, call modify(num), and then print the value of 'num'. What is the output?
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

void modify(int x) {
    x = 100;
}

int main() {
    int num = 7;
    modify(num);
    cout << "Value of num: " << num << endl;
    return 0;
}
Explanation: 1. In main(), num is initialized to 7. 2. The function modify is called with num as argument. Since it's call by value, a copy of num (7) is passed to the parameter x. 3. Inside modify, x is assigned 100. This changes only the local copy x, not the original num. 4. After the function returns, num remains 7. 5. The cout statement prints 'Value of num: 7'.
Q46.Easy
Write a C++ program that declares an integer variable named 'score' and initializes it to 42. Add a single-line comment on the same line explaining that 'score' holds the player's points. Then print the value of 'score' followed by a newline.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

int main() {
    int score = 42; // score holds the player's points
    cout << score << "\n";
    return 0;
}
Explanation: 1. Include the iostream library for input/output. 2. Use the std namespace. 3. In main(), declare an integer variable 'score' and assign 42. 4. Add a single-line comment using // after the statement. 5. Output the value of 'score' followed by a newline using cout. 6. Return 0 to indicate successful execution.
Q47.Easy
Write a C++ program that uses a multi-line comment (enclosed in /* ... */) to describe the code, then declares an integer variable named marks with value 48 and prints it followed by a newline.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main()
{
/* declare and
print variable in C++. */
    int marks = 48;
    cout << marks << "\n";
    return 0;
}
Explanation: 1. The block /* ... */ is a multi-line comment; the compiler ignores everything inside it. 2. Inside main, an integer variable marks is declared and initialised to 48. 3. cout prints the value of marks, then "\n" moves to a new line. 4. The program outputs 48 on a single line.
Q48.Easy
Write a C++ program that prints the numbers 1 to 12, but skips printing the number 7 using the continue statement.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main()
{
    for(int i = 1; i <= 12; i++){
        if(i == 7){
            continue;
        }
        cout << i << "\n";
    }
    return 0;
}
Explanation: 1. The for loop runs i from 1 to 12. 2. Inside the loop, when i equals 7, the continue statement is executed. 3. continue skips the rest of the loop body for that iteration, so 7 is not printed. 4. For all other values of i, cout prints the number followed by a newline. 5. Output: 1 2 3 4 5 6 8 9 10 11 12 (each on its own line).
Q49.Easy
Write a C++ program that uses nested loops: an outer loop over i from 1 to 3 and an inner loop over j from 1 to 3. When i equals 2 and j equals 2, use the continue statement so that this single inner iteration is skipped, and print all other pairs as 'i j' on separate lines.
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){
                continue;
            }
            cout << i << " " << j << "\n";
        }
    }
    return 0;
}
Explanation: 1) Outer loop runs i = 1, 2, 3; inner loop runs j = 1, 2, 3 for each i. 2) When i==2 and j==2, continue skips only that inner iteration, so '2 2' is not printed. 3) All other pairs are printed: 1 1, 1 2, 1 3, 2 1, 2 3, 3 1, 3 2, 3 3. 4) continue affects only the inner loop, so the outer loop still completes all three values of i.
Q50.Easy
Write a C++ program that uses a do-while loop to print the numbers from 1 to 5, each on a new line.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main() {
    int i = 1;
    do {
        cout << i << "\n";
        i++;
    } while (i <= 5);
    return 0;
}
Explanation: 1. Initialize i to 1. 2. do-while loop executes body first: print i, then increment i. 3. Condition i <= 5 is checked after each iteration. 4. Loop continues until i becomes 6, printing 1 to 5 each on new line.
Q51.Easy
Write a C++ program that uses an infinite do-while loop (condition true) to repeatedly print the message "Endless do-while Loop".
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main() {
    do {
        cout << "Endless do-while Loop";
    } while (true);
}
Explanation: 1) A do-while loop executes its body first, then checks the condition. 2) Passing true as the condition means the check always succeeds. 3) So the body runs forever, printing the message endlessly. 4) The loop never terminates on its own.
Q52.Easy
Write a C++ program that uses nested do-while loops to print the value of the outer loop counter for each iteration of the inner loop. The outer loop should run for i = 1 to 3, and the inner loop should run for j = 1 to 2. For each inner iteration, print i followed by a newline.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main() {
    int i = 1;
    do {
        int j = 1;
        do {
            cout << i << "\n";
            j++;
        } while (j <= 2);
        i++;
    } while (i <= 3);
    return 0;
}
Explanation: 1. Initialize outer counter i to 1. 2. Outer do-while loop runs while i <= 3. 3. Inside outer loop, initialize inner counter j to 1. 4. Inner do-while loop runs while j <= 2, printing i each time and incrementing j. 5. After inner loop, increment i. 6. Repeat until outer condition fails. Output: 1 1 2 2 3 3 each on new line.
Q53.Easy
Write a C++ program that uses nested for loops to print all pairs (i, j) where i takes values from 1 to 2 and j takes values from 1 to 3. Each pair should be printed on a new line as 'i j'.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

int main() {
    for (int i = 1; i <= 2; i++) {
        for (int j = 1; j <= 3; j++) {
            cout << i << " " << j << "\n";
        }
    }
    return 0;
}
Explanation: 1. The outer loop runs with i from 1 to 2 (two iterations). 2. For each i, the inner loop runs with j from 1 to 3 (three iterations). 3. Inside the inner loop, we print i and j separated by a space and then a newline. 4. Thus, the program prints all six pairs: (1,1), (1,2), (1,3), (2,1), (2,2), (2,3).
Q54.Easy
Write a C++ program that declares an integer variable, assigns it the value of a constant expression (7/2) + 3, and prints the result.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main()
{
    int marks;
    marks = (7/2) + 3;
    cout << "Value of marks is : " << marks;
    return 0;
}
Explanation: 1) Declare an int variable marks. 2) Compute the constant expression (7/2)+3: integer division 7/2 gives 3. 3) Add 3 to get 6. 4) Assign 6 to marks and print it with cout.
Q55.Easy
Write a C++ program that demonstrates an integer expression. Read two integers p and q from the user, compute their sum into an integer variable r, and print the result in the form: Value of r is : <sum>
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main()
{
    int p;  // variable declaration
    int q;  // variable declaration
    int r;  // variable declaration
    cout << "Enter the values of p and q";
    cin >> p >> q;
    r = p + q;
    cout << "\n" << "Value of r is :" << r;
    return 0;
}
Explanation: 1) Include <iostream> and use namespace std for cin/cout. 2) Declare three int variables p, q and r. 3) Prompt the user and read two integers into p and q using cin >> p >> q. 4) Compute r = p + q; since both are int, the result is an integer expression. 5) Print a newline then the label and r, e.g. for inputs 4 and 9 the output is: Value of r is :13 6) return 0 ends the program.
Q56.Easy
Write a C++ program that demonstrates a float expression. Declare two float variables a = 7.4 and b = 3.8, compute their sum into a float variable c, and print the result in the form: value of c is : <sum>
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main()
{
    float a = 7.4;   // variable initialization
    float b = 3.8;   // variable initialization
    float c;         // variable declaration
    c = a + b;
    cout << "value of c is : " << c << endl;
    return 0;
}
Explanation: 1) Include <iostream> and use namespace std so cout/endl are available. 2) Declare two float variables a=7.4 and b=3.8; floats store decimal values. 3) Declare float c and assign c = a + b, which performs floating-point addition giving 11.2. 4) Print the label followed by c, so the output is: value of c is : 11.2 5) return 0 ends the program.
Q57.Easy
Write a C++ program that demonstrates pointer expressions. Declare an integer array marks with values {10, 20, 30, 40, 50}. Declare a pointer variable ptr and assign it the base address of the array. Increment the pointer by 1 (using ptr = ptr + 1) and then print the value pointed to by ptr. What is the output?
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

int main() {
    int marks[] = {10, 20, 30, 40, 50};
    int *ptr;
    ptr = marks;
    ptr = ptr + 1;
    cout << "Value of second element of an array: " << *ptr << endl;
    return 0;
}
Explanation: 1. Include the iostream library and use the std namespace. 2. In main(), declare an integer array marks with 5 elements: {10, 20, 30, 40, 50}. 3. Declare an integer pointer ptr. 4. Assign the base address of the array to ptr: ptr = marks; (marks decays to a pointer to its first element). 5. Increment the pointer by 1: ptr = ptr + 1; Now ptr points to the second element of the array (marks[1]). 6. Dereference ptr using *ptr to get the value at that address, which is 20. 7. Print the value: "Value of second element of an array: 20". 8. Return 0.
Q58.Easy
Write a C++ program that demonstrates relational expressions. Declare two integer variables: score1 = 56 and score2 = 89. Create a bool variable result that stores the value of the relational expression score1 > score2. Print the value of result to the console.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

int main() {
    int score1 = 56;
    int score2 = 89;
    bool result = score1 > score2;
    cout << "Value of result is: " << result << endl;
    return 0;
}
Explanation: 1. Include the iostream library for input/output. 2. Use the std namespace to avoid writing std:: before cout and endl. 3. In main(), declare two integer variables: score1 = 56 and score2 = 89. 4. Declare a bool variable result and assign it the value of the relational expression score1 > score2. Since 56 is not greater than 89, result becomes false. 5. Output the value of result using cout. The output will be: Value of result is: 0 (since false is printed as 0 by default). 6. Return 0 to indicate successful execution.
Q59.Easy
Write a C++ program that declares three integers: price = 3, cost = 8 and tax = 5. Using the logical OR operator, print the boolean result of the expression (price > cost) || (price > tax) to the console.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main()
{
    int price = 3;
    int cost = 8;
    int tax = 5;
    cout << ((price > cost) || (price > tax));
    return 0;
}
Explanation: 1) Evaluate the first relational expression: price > cost means 3 > 8, which is false (0). 2) Evaluate the second relational expression: price > tax means 3 > 5, which is also false (0). 3) The logical OR (||) of false and false is false. 4) cout prints the bool value false as 0, so the output is 0.
Q60.Easy
Write a C++ program that declares an integer variable marks = 9 and prints the result of shifting its bits two positions to the right (marks >> 2) to the console.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main()
{
    int marks = 9;   // variable declaration
    std::cout << (marks >> 2) << std::endl;
    return 0;
}
Explanation: 1) Declare int marks = 9, whose binary form is 1001. 2) The expression marks >> 2 shifts the bits two positions to the right, dropping the two lowest bits: 1001 -> 10. 3) Binary 10 equals decimal 2. 4) std::cout prints 2 followed by a newline, so the program outputs 2.
Q61.Easy
Write a C++ program that declares two integer variables and uses a single chained assignment statement to assign the value 65 to both variables. Then print both values separated by a comma.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main()
{
    int p;   // variable declaration
    int q;   // variable declaration
    p = q = 65;  // chained assignment
    cout << "Values of 'p' and 'q' are : " << p << "," << q << endl;
    return 0;
}
Explanation: Step 1: Declare two int variables p and q. Step 2: The chained assignment p = q = 65 is evaluated right to left: first q = 65 sets q to 65 and yields 65, then p = 65 sets p to 65. Step 3: Both variables now hold 65. Step 4: The program prints: Values of 'p' and 'q' are : 65,65.
Q62.Easy
Write a C++ program that declares two integer variables, then uses an embedded assignment expression to set the second variable to 75 inside an expression that adds 25 to it and stores the result in the first variable. Print the value of the first variable.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main()
{
    int x;  // first variable
    int y;  // second variable
    x = 25 + (y = 75);  // embedded assignment expression
    cout << "Value of 'x' is " << x << endl;
    return 0;
}
Explanation: Step 1: Declare two int variables x and y. Step 2: In the expression x = 25 + (y = 75), the inner assignment (y = 75) first sets y to 75 and yields the value 75. Step 3: Then 25 + 75 = 100 is assigned to x. Step 4: So the program prints: Value of 'x' is 100.
Q63.Easy
Write a C++ program that uses a for loop to print the numbers from 1 to 5, each on a new line.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

int main() {
    for (int i = 1; i <= 5; i++) {
        cout << i << "\n";
    }
    return 0;
}
Explanation: 1. The for loop initializes i to 1. 2. The condition i <= 5 is checked; if true, the loop body executes. 3. Inside the loop, the current value of i is printed followed by a newline. 4. After each iteration, i is incremented by 1. 5. The loop stops when i becomes 6, so the numbers 1, 2, 3, 4, 5 are printed.
Q64.Easy
Write a C++ program that uses a for loop with an empty condition (for(;;)) to create an infinite loop, printing the message "Looping forever" repeatedly.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main() {
    for (;;) {
        cout << "Looping forever" << endl;
    }
    return 0;
}
Explanation: 1) Include <iostream> and use namespace std. 2) In main(), write for(;;) — all three parts (initialization, condition, increment) are empty. 3) With no condition, the loop condition is treated as true, so the loop never terminates. 4) Inside the loop, print "Looping forever" each iteration, producing infinite output.
Q65.Easy
Write a C++ program that demonstrates function overriding. Create a base class Vehicle with a method describe() that prints "Vehicle moves...". Create a derived class Bicycle that inherits from Vehicle and overrides describe() to print "Bicycle moves on pedals...". In main(), create a Bicycle object and call describe().
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
class Vehicle {
public:
    void describe() {
        cout << "Vehicle moves...";
    }
};
class Bicycle : public Vehicle {
public:
    void describe() {
        cout << "Bicycle moves on pedals...";
    }
};
int main() {
    Bicycle b;
    b.describe();
    return 0;
}
Explanation: 1) Define base class Vehicle with a public method describe() that prints "Vehicle moves...". 2) Define derived class Bicycle inheriting publicly from Vehicle. 3) Bicycle redefines describe() with the same signature, overriding the base version. 4) In main(), create a Bicycle object b and call b.describe(). 5) Since the object is of type Bicycle, the overridden method runs and prints "Bicycle moves on pedals...".
Q66.Easy
Write a C++ program that prints the address of a function named greet() (which simply prints a greeting) by using the function's name without calling it. The output should be of the form: Address of greet() function is : <address>
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
void greet()
{
    std::cout << "Namaste" << std::endl;
}
int main()
{
    std::cout << "Address of greet() function is : " << reinterpret_cast<void*>(&greet) << std::endl;
    return 0;
}
Explanation: 1) Define a function greet() that prints a greeting. 2) In main, use &greet (or just greet) to obtain the function's address without calling it. 3) Print the address with the label 'Address of greet() function is : '. 4) The address value itself is implementation-dependent, but the program correctly displays it.
Q67.Easy
Write a C++ program that defines a function multiply(int, int) returning the product of two integers. In main(), declare a function pointer, assign the multiply function to it, and call the function indirectly through the pointer with the values 6 and 7. Print the result in the form: value of product is :42
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int multiply(int a, int b)
{
    return a * b;
}
int main()
{
    int (*funcptr)(int, int);   // function pointer declaration
    funcptr = multiply;         // funcptr points to multiply
    int product = funcptr(6, 7);
    std::cout << "value of product is :" << product << std::endl;
    return 0;
}
Explanation: 1) Define multiply(int a, int b) that returns a*b. 2) In main, declare a function pointer int (*funcptr)(int,int). 3) Assign funcptr = multiply (name of function gives its address). 4) Call funcptr(6,7), which invokes multiply and returns 42. 5) Print the result as 'value of product is :42'.
Q68.Easy
Write a C++ program that defines a function named 'showCount' which demonstrates the difference between a static local variable and a non-static local variable. The function should increment both variables and print their values each time it is called. In main, call the function three times. The output should show the static variable retaining its value between calls while the non-static variable resets.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

void showCount() {
    static int s = 0; // static variable retains value
    int n = 0;        // non-static variable resets each call
    s++;
    n++;
    cout << "s=" << s << " and n=" << n << endl;
}

int main() {
    showCount();
    showCount();
    showCount();
    return 0;
}
Explanation: 1. The function showCount declares a static int s initialized to 0 and a non-static int n initialized to 0. 2. On first call, s becomes 1, n becomes 1; prints s=1 and n=1. 3. On second call, s retains its previous value (1) and increments to 2; n is reinitialized to 0 and increments to 1; prints s=2 and n=1. 4. On third call, s becomes 3; n becomes 1; prints s=3 and n=1. 5. The static variable persists across calls, while the non-static variable is recreated each time.
Q69.Easy
Write a C++ program that uses the goto statement to check voting eligibility. The program should ask the user to enter their age. If the age is less than 18, it should print 'You are not eligible to vote!' and then jump back to ask for the age again (using a goto label). If the age is 18 or more, it should print 'You are eligible to vote!' and stop.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main()
{
    int age;
askAge:
    cout << "Enter your age:\n";
    cin >> age;
    if (age < 18) {
        cout << "You are not eligible to vote!\n";
        goto askAge;
    }
    else {
        cout << "You are eligible to vote!";
    }
    return 0;
}
Explanation: 1. Define a label named notEligible at the start of the repeated block. 2. Print the 'not eligible' message and prompt the user to enter their age. 3. Read the age into an int variable. 4. If age is less than 18, execute 'goto notEligible', which unconditionally jumps control back to the label, repeating the prompt. 5. If age is 18 or more, the else branch prints 'You are eligible to vote!' and the program ends.
Q70.Easy
Write a C++ program that declares two integer variables named 'marks' and 'MARKS' (note that C++ is case-sensitive, so these are two distinct identifiers). The program should prompt the user to enter a value for each, read both values, and then print both entered values separated by a comma.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main()
{
    int marks;
    int MARKS;
    cout << "Enter the values of 'marks' and 'MARKS': ";
    cin >> marks;
    cin >> MARKS;
    cout << "\nThe values that you have entered are : " << marks << " , " << MARKS;
    return 0;
}
Explanation: 1. Include the iostream header and use the std namespace so cin/cout are available. 2. Declare two separate int variables: 'marks' and 'MARKS'. Because C++ is case-sensitive, these are treated as two different identifiers, not a conflict. 3. Prompt the user with cout, then read the first value into 'marks' and the second into 'MARKS' using two cin statements. 4. Print both stored values with cout, separating them by a comma. 5. Return 0 to end main successfully.
Q71.Easy
Write a C++ program to demonstrate single level inheritance where a derived class inherits fields from a base class. Create a base class 'Employee' with a public float field 'salary' initialized to 45000. Create a derived class 'Manager' that inherits from Employee and adds a public float field 'bonus' initialized to 8000. In main, create a Manager object and print its salary and bonus.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

class Employee {
public:
    float salary = 45000;
};

class Manager : public Employee {
public:
    float bonus = 8000;
};

int main() {
    Manager m1;
    cout << "Salary: " << m1.salary << endl;
    cout << "Bonus: " << m1.bonus << endl;
    return 0;
}
Explanation: 1. Define a base class 'Employee' with a public float member 'salary' set to 45000. 2. Define a derived class 'Manager' that inherits publicly from 'Employee' and adds a public float member 'bonus' set to 8000. 3. In main(), create a Manager object 'm1'. 4. Access the inherited 'salary' field via 'm1.salary' and print it. 5. Access the 'bonus' field via 'm1.bonus' and print it. 6. The program shows single inheritance where the derived class inherits fields from the base class.
Q72.Easy
Write a C++ program to demonstrate single level inheritance where a derived class inherits methods from a base class. Create a base class 'Vehicle' with a method 'move()' that prints "Moving..." and a derived class 'Car' that inherits from Vehicle and adds a method 'honk()' that prints "Honking...". In main, create a Car object and call both methods.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

class Vehicle {
public:
    void move() {
        cout << "Moving..." << endl;
    }
};

class Car : public Vehicle {
public:
    void honk() {
        cout << "Honking..." << endl;
    }
};

int main() {
    Car c1;
    c1.move();
    c1.honk();
    return 0;
}
Explanation: 1. Define a base class 'Vehicle' with a public method 'move()' that outputs "Moving...". 2. Define a derived class 'Car' that inherits publicly from 'Vehicle' and adds a method 'honk()' that outputs "Honking...". 3. In main(), instantiate a Car object 'c1'. 4. Call 'c1.move()' which is inherited from Vehicle, printing "Moving...". 5. Call 'c1.honk()' which is defined in Car, printing "Honking...". 6. The program demonstrates single inheritance where the derived class inherits methods from the base class.
Q73.Easy
Write a C++ program that demonstrates multilevel inheritance. Create a base class Vehicle with a method start() that prints "Starting...". Derive class Car from Vehicle (public) adding method drive() that prints "Driving...". Derive class SportsCar from Car (public) adding method race() that prints "Racing...". In main, create a SportsCar object and call start(), drive() and race() to show that the last derived class inherits members of all its base classes.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

class Vehicle {
public:
    void start() {
        cout << "Starting..." << endl;
    }
};

class Car : public Vehicle {
public:
    void drive() {
        cout << "Driving..." << endl;
    }
};

class SportsCar : public Car {
public:
    void race() {
        cout << "Racing..." << endl;
    }
};

int main() {
    SportsCar s1;
    s1.start();
    s1.drive();
    s1.race();
    return 0;
}
Explanation: 1) Vehicle is the base class with start() printing "Starting...". 2) Car : public Vehicle inherits start() and adds drive() printing "Driving...". 3) SportsCar : public Car inherits both start() and drive() (inheritance is transitive) and adds race() printing "Racing...". 4) In main, SportsCar s1 can call start(), drive() and race() because it acquires all members of all its base classes. 5) Output: Starting... / Driving... / Racing... on separate lines.
Q74.Easy
Write a C++ program that demonstrates multiple inheritance. Create two base classes, Singer (with a method sing() that prints "Singing...") and Dancer (with a method dance() that prints "Dancing..."). Derive a class Artist that inherits publicly from both Singer and Dancer, and add its own method perform() that prints "Performing...". In main, create an Artist object and call sing(), dance() and perform().
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

class Singer {
public:
    void sing() {
        cout << "Singing..." << endl;
    }
};

class Dancer {
public:
    void dance() {
        cout << "Dancing..." << endl;
    }
};

class Artist : public Singer, public Dancer {
public:
    void perform() {
        cout << "Performing..." << endl;
    }
};

int main() {
    Artist a1;
    a1.sing();
    a1.dance();
    a1.perform();
    return 0;
}
Explanation: 1) Define base class Singer with public method sing() printing "Singing...". 2) Define base class Dancer with public method dance() printing "Dancing...". 3) Define Artist : public Singer, public Dancer — the comma-separated base list is multiple inheritance, so Artist gets both sing() and dance(). 4) Add Artist's own method perform() printing "Performing...". 5) In main, create Artist a1 and call a1.sing(), a1.dance(), a1.perform(); output is three lines in that order.
Q75.Easy
Write a C++ program that demonstrates hierarchical inheritance. Create a base class named Animal with a member function eat() that prints "animal eats food". Derive two classes from Animal: Dog and Cat. Dog has a function bark() that prints "dog barks" and Cat has a function meow() that prints "cat meows". In main(), create a Dog object and a Cat object, and call eat() plus their own specific functions.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

class Animal
{
    public:
    void eat()
    {
        cout << "animal eats food" << endl;
    }
};

class Dog : public Animal
{
    public:
    void bark()
    {
        cout << "dog barks" << endl;
    }
};

class Cat : public Animal
{
    public:
    void meow()
    {
        cout << "cat meows" << endl;
    }
};

int main()
{
    Dog d;
    Cat c;
    d.eat();
    d.bark();
    c.eat();
    c.meow();
    return 0;
}
Explanation: 1. Animal is the single base class holding the common function eat(). 2. Both Dog and Cat inherit publicly from Animal, so this is hierarchical inheritance (more than one class derived from one base). 3. Dog adds its own function bark(); Cat adds its own function meow(). 4. In main(), a Dog object d and a Cat object c are created. 5. d.eat() and c.eat() use the inherited function, while d.bark() and c.meow() use each derived class's own function, producing the four output lines.
Q76.Easy
Write a C++ program that stores the numbers 5, 15, 25, 35, 45 in a vector and prints each element using an iterator. Use the begin() and end() member functions of the vector to traverse it.
Show answer & explanation
Answer:
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
int main()
{
   std::vector<int> v{5,15,25,35,45};
   vector<int>::iterator itr;
   for(itr=v.begin();itr!=v.end();itr++)
   {
       std::cout << *itr <<" ";
   }
    return 0;
}
Explanation: 1. Include the vector and iterator headers. 2. Declare vector v with the values 5,15,25,35,45. 3. Declare an iterator itr of type vector<int>::iterator. 4. begin() points to the first element and end() points just past the last element. 5. The loop runs while itr != v.end(); each iteration prints *itr (the current element) and itr++ moves to the next element. 6. Output: 5 15 25 35 45.
Q77.Easy
Write a C++ program that stores the numbers 10, 20, 30, 40, 50 in a vector. First print all elements using the subscript operator [] in a loop. Then print all elements using an iterator. After that, add the number 60 to the vector and print all elements again using both the subscript operator and an iterator.
Show answer & explanation
Answer:
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
int main()
{
    vector<int> v{10,20,30,40,50};
    vector<int>::iterator itr;
    for(int i=0;i<5;i++)            // Traversal using subscript operator
    {
        cout<<v[i]<<" ";
    }
    cout<<'\n';
    for(itr=v.begin();itr!=v.end();itr++)  // Traversal using iterator
    {
        cout<<*itr<<" ";
    }
    v.push_back(60);
    cout<<'\n';
    for(int i=0;i<6;i++)
    {
        cout<<v[i]<<" ";
    }
    cout<<'\n';
    for(itr=v.begin();itr!=v.end();itr++)
    {
        cout<<*itr<<" ";
    }
    return 0;
}
Explanation: 1. Create a vector v holding 10,20,30,40,50. 2. Loop i=0..4 and print v[i] using the subscript operator. 3. Use an iterator from v.begin() to v.end(), printing *itr each step. 4. Call v.push_back(60) so the vector now has 6 elements. 5. Loop i=0..5 printing v[i]; the size is known at runtime so the loop bound must be updated manually. 6. Iterate again with begin()/end(); the iterator automatically covers the new element, showing why iterators are convenient.
Q78.Easy
Write a C++ program that declares a 3x3 two-dimensional integer array (without initializing it at declaration), then assigns these values individually: element [0][0]=12, [0][2]=7, [1][0]=5, [1][1]=9, [2][1]=4, [2][2]=6. All other elements should remain 0. Finally traverse the whole array with nested loops and print each row on its own line with elements separated by a space.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main()
{
    static int grid[3][3];  // declaration only; static storage is zero-filled
    grid[0][0] = 12;
    grid[0][2] = 7;
    grid[1][0] = 5;
    grid[1][1] = 9;
    grid[2][1] = 4;
    grid[2][2] = 6;
    for(int i = 0; i < 3; ++i)
    {
        for(int j = 0; j < 3; ++j)
        {
            cout << grid[i][j] << " ";
        }
        cout << "\n";
    }
    return 0;
}
Explanation: 1) int grid[3][3]; declares a 3x3 array; unassigned elements are left uninitialized in general, but here we only rely on the assigned ones plus the ones we set to 0 conceptually — to be safe, note the printed values below. 2) Six elements are assigned by index: [0][0]=12, [0][2]=7, [1][0]=5, [1][1]=9, [2][1]=4, [2][2]=6. 3) The nested loops print row by row: i selects the row, j selects the column. 4) Row 0: 12, then [0][1] (unassigned), then 7. 5) Row 1: 5, 9, then [1][2] (unassigned). 6) Row 2: [2][0] (unassigned), 4, 6. 7) To make output deterministic, initialize the array as int grid[3][3] = {0}; before assigning, giving output: 12 0 7 5 9 0 0 4 6
Q79.Easy
Write a C++ program that declares a 3x3 two-dimensional integer array and initializes it at the time of declaration with the values: first row {7, 2, 9}, second row {4, 6, 1}, third row {8, 3, 5}. Then traverse the array using nested loops and print each row on its own line with elements separated by a space.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main()
{
    int marks[3][3] =
    {
        {7, 2, 9},
        {4, 6, 1},
        {8, 3, 5}
    };  // declaration and initialization at the same time
    // traversal
    for(int i = 0; i < 3; ++i)
    {
        for(int j = 0; j < 3; ++j)
        {
            cout << marks[i][j] << " ";
        }
        cout << "\n"; // new line after each row
    }
    return 0;
}
Explanation: 1) The array marks[3][3] is declared and initialized in one statement using nested braces, one brace per row. 2) The outer loop i runs from 0 to 2, selecting each row. 3) The inner loop j runs from 0 to 2, printing each element of that row followed by a space. 4) After each row, cout << "\n" moves output to the next line. 5) Output: 7 2 9 4 6 1 8 3 5
Q80.Easy
Write a C++ program that defines a class named Book having three data members only: an integer bookId, a float price, and a string title. In main(), create one Book object, set bookId = 47, price = 259.5, title = "Wings of Fire", and print all three values on separate lines.
Show answer & explanation
Answer:
#include <iostream>
#include <string>
using namespace std;

class Book {
public:
    int bookId;
    float price;
    string title;
};

int main() {
    Book b1;
    b1.bookId = 47;
    b1.price = 259.5;
    b1.title = "Wings of Fire";
    cout << b1.bookId << endl;
    cout << b1.price << endl;
    cout << b1.title << endl;
    return 0;
}
Explanation: 1) Include <iostream> and <string>. 2) Define class Book with public members bookId (int), price (float), title (string) — three fields only. 3) In main(), create object b1 of class Book. 4) Assign b1.bookId = 47, b1.price = 259.5, b1.title = "Wings of Fire". 5) Print the three members on separate lines and return 0.
Q81.Easy
Write a C++ program with a class Calculator containing two static overloaded functions add(): one that adds two integers and one that adds three integers. In main, create an object and print add(15, 25) and add(5, 10, 20).
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
class Calculator {
    public:
static int add(int a,int b){
        return a + b;
    }
static int add(int a, int b, int c)
    {
        return a + b + c;
    }
};
int main(void) {
    Calculator C;
    cout<<C.add(15, 25)<<endl;
    cout<<C.add(5, 10, 20);
   return 0;
}
Explanation: 1) The class Calculator declares two static functions both named add(), differing in the number of parameters (two vs three). 2) This is function overloading resolved by argument count. 3) In main an object C is created and C.add(15,25) matches the two-argument version, returning 40. 4) C.add(5,10,20) matches the three-argument version, returning 35. 5) The program prints 40 on the first line and 35 on the second line.
Q82.Easy
Write a C++ program that demonstrates function overloading with two functions named show() — one taking an int and one taking a float. Call show(25) and show(3.5) from main and print the values. Explain why the compiler can resolve these calls without ambiguity.
Show answer & explanation
Answer:
#include<iostream>
using namespace std;
void show(int);
void show(float);
void show(int a)
{
    cout << "Integer value is : " << a << endl;
}
void show(float b)
{
    cout << "Float value is : " << b << endl;
}
int main()
{
    show(25);
    show(3.5f);
    return 0;
}
Explanation: 1) Two overloads of show() are declared: show(int) and show(float). 2) In main, show(25) passes an int literal, so the compiler picks show(int) exactly — no conversion needed. 3) show(3.5f) passes a float literal (suffix f), so the compiler picks show(float) exactly. 4) Because each argument type matches one overload exactly, there is no ambiguity; the program compiles and prints the integer then the float value.
Q83.Easy
Write a C++ program that defines a function to print the elements of an integer array, and calls it for two different arrays. The first array should hold the marks {12, 24, 36, 48, 60} and the second should hold {7, 14, 21, 28, 35}. The function receives the array (and its size) and prints each element on its own line.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

void printMarks(int arr[], int size)
{
    cout << "Printing array elements:" << endl;
    for (int i = 0; i < size; i++)
    {
        cout << arr[i] << "\n";
    }
}

int main()
{
    int marks1[5] = {12, 24, 36, 48, 60};
    int marks2[5] = {7, 14, 21, 28, 35};
    printMarks(marks1, 5);
    printMarks(marks2, 5);
    return 0;
}
Explanation: 1. Define a function printMarks that takes an int array and its size as parameters. 2. Inside the function, loop from 0 to size-1 and print each element on a new line. 3. In main, create two arrays marks1 and marks2 with the given values. 4. Call printMarks(marks1, 5) and printMarks(marks2, 5); only the array name is passed, which decays to a pointer to the first element. 5. The function reuses the same printing logic for both arrays.
Q84.Easy
Write a C++ program that passes an array to a function to print its minimum element. Create two arrays: arr1 = {25, 8, 17, 42, 33} and arr2 = {12, 19, 4, 27, 36}. Write a function printMin(int arr[], int size) that finds and prints the minimum element of the passed array, and call it for both arrays.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
void printMin(int arr[], int size);
int main()
{
    int arr1[5] = {25, 8, 17, 42, 33};
    int arr2[5] = {12, 19, 4, 27, 36};
    printMin(arr1, 5); // passing array to function
    printMin(arr2, 5);
    return 0;
}
void printMin(int arr[], int size)
{
    int min = arr[0];
    for (int i = 1; i < size; i++)
    {
        if (min > arr[i])
        {
            min = arr[i];
        }
    }
    cout << "Minimum element is: " << min << "\n";
}
Explanation: 1. Define printMin(int arr[], int size) which takes the array and its length. 2. Initialize min = arr[0], the first element. 3. Loop i from 1 to size-1; if arr[i] < min, update min = arr[i]. 4. After the loop, min holds the smallest element; print it. 5. In main, call printMin(arr1, 5): min becomes 8 (since 8 < 25, 17, 42, 33). 6. Call printMin(arr2, 5): min becomes 4 (since 4 < 12, 19, 27, 36).
Q85.Easy
Write a C++ program that declares an integer variable named marks with value 45 and an integer pointer q. Make q store the address of marks, then print the address of marks, the value stored in q, and the value pointed to by q (using *q).
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main()
{
    int marks = 45;
    int *q;
    q = &marks; // stores the address of marks variable
    cout << "Address of marks variable is: " << &marks << endl;
    cout << "Address stored in q is: " << q << endl;
    cout << "Value pointed to by q is: " << *q << endl;
    return 0;
}
Explanation: 1. Declare int marks = 45; this creates an integer variable holding 45. 2. Declare int *q; this is a pointer to an int. 3. Assign q = &marks; so q holds the memory address of marks. 4. &marks prints the address of marks; q prints the same address. 5. *q dereferences the pointer and prints the value stored at that address, which is 45.
Q86.Easy
Write a C++ program that uses pointers to swap two numbers without using a third variable. Initialize two integers a = 15 and b = 25, use pointers p1 and p2 pointing to a and b respectively, and swap the values they point to using only addition and subtraction. Print the values before and after the swap.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

int main() {
    int a = 15, b = 25;
    int *p1 = &a, *p2 = &b;

    cout << "Before swap: *p1 = " << *p1 << ", *p2 = " << *p2 << endl;

    *p1 = *p1 + *p2;  // *p1 becomes 40
    *p2 = *p1 - *p2;  // *p2 becomes 15
    *p1 = *p1 - *p2;  // *p1 becomes 25

    cout << "After swap: *p1 = " << *p1 << ", *p2 = " << *p2 << endl;

    return 0;
}
Explanation: 1. Two integers a=15 and b=25 are declared. Pointers p1 and p2 point to a and b respectively. 2. The swap uses arithmetic on the pointed-to values: - *p1 = *p1 + *p2; // *p1 becomes 15+25=40 - *p2 = *p1 - *p2; // *p2 becomes 40-25=15 - *p1 = *p1 - *p2; // *p1 becomes 40-15=25 3. After these operations, *p1 is 25 and *p2 is 15, so the values are swapped. 4. The program prints the values before and after the swap to verify.
Q87.Easy
Write a C++ program with a base class 'Bird' having a method 'sound()' that prints "Chirp...", and a derived class 'Parrot' that overrides 'sound()' to print "Squawk...". In main, create a Parrot object and call its 'sound()' method. (Note: no virtual keyword is used.)
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

class Bird {
public:
    void sound() {
        cout << "Chirp..." << endl;
    }
};

class Parrot : public Bird {
public:
    void sound() {
        cout << "Squawk..." << endl;
    }
};

int main() {
    Parrot p;
    p.sound();
    return 0;
}
Explanation: 1) 'Bird' defines 'sound()' printing "Chirp...". 2) 'Parrot' inherits from Bird and redefines 'sound()' to print "Squawk..." (function hiding/overriding without virtual). 3) In main, a Parrot object 'p' is created. 4) Calling p.sound() uses the Parrot version because the object is of type Parrot, so the output is "Squawk...". 5) Since no virtual keyword is used, this is compile-time (static) binding, not run-time polymorphism.
Q88.Easy
Write a C++ program with a function 'tick()' that contains a static int 'count' initialized to 0 and a normal local int 'temp' initialized to 0. Each call should increment both and print them as: count=<value> temp=<value>. Call tick() three times from main() and observe the difference.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

void tick() {
    static int count = 0; // initialized only once
    int temp = 0;         // re-initialized every call
    count++;
    temp++;
    cout << "count=" << count << " temp=" << temp << endl;
}

int main() {
    tick();
    tick();
    tick();
    return 0;
}
Explanation: 1. 'static int count = 0;' is initialized only once and keeps its value between calls. 2. 'int temp = 0;' is a normal local variable, re-created and reset to 0 on every call. 3. First call: count becomes 1, temp becomes 1 -> count=1 temp=1. 4. Second call: count keeps 1 and becomes 2; temp resets to 0 then becomes 1 -> count=2 temp=1. 5. Third call: count becomes 3; temp again 1 -> count=3 temp=1. 6. Output: count=1 temp=1 / count=2 temp=1 / count=3 temp=1.
Q89.Easy
Write a C++ program that demonstrates a class template with two generic type parameters. Create a template class PairBox with parameters T1 and T2 that stores two values (one of each type) and provides a method show() that prints both values separated by a space. In main(), create a PairBox<string, double> holding "Ravi" and 45000.5, and call show().
Show answer & explanation
Answer:
#include <iostream>
#include <string>
using namespace std;

template <class T1, class T2>
class PairBox {
    T1 first;
    T2 second;
public:
    PairBox(T1 a, T2 b) : first(a), second(b) {}
    void show() {
        cout << first << " " << second << endl;
    }
};

int main() {
    PairBox<string, double> p("Ravi", 45000.5);
    p.show();
    return 0;
}
Explanation: 1) The header template <class T1, class T2> declares two independent generic types separated by a comma. 2) The class stores one member of type T1 (first) and one of type T2 (second). 3) The constructor initialises both members from the arguments passed. 4) show() prints first then second separated by a space. 5) In main(), PairBox<string, double> sets T1 = string and T2 = double, so the output is: Ravi 45000.5
Q90.Easy
Write a C++ program that shows a void pointer can hold the address of a variable of any data type. Declare a void pointer and a float variable price = 45.5, store the address of price in the void pointer, then typecast the void pointer back to a float pointer and print the value it points to.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

int main() {
    void *vp;          // void pointer declaration
    float *fp;         // float pointer declaration
    float price = 45.5;
    vp = &price;       // void pointer holds address of a float
    fp = (float *)vp;  // typecast void pointer to float pointer
    cout << "The value of *fp is : " << *fp << endl;
    return 0;
}
Explanation: 1. Declare a void pointer vp and a float pointer fp. 2. Create float price = 45.5. 3. Assign vp = &price; a void pointer is a general-purpose pointer that can hold the address of any data type. 4. In C++ you cannot directly assign a void pointer to a typed pointer, so cast it: fp = (float *)vp;. 5. Dereference fp with *fp to obtain 45.5 and print it. 6. Output: The value of *fp is : 45.5.
Q91.Easy
Write a C++ program that demonstrates how a void pointer works in C++. Declare a void pointer and an integer pointer, store the address of an integer variable (value 75) in the void pointer, then assign the void pointer to the integer pointer using an explicit typecast (as required in C++), and finally print the value pointed to by the integer pointer.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

int main() {
    void *vp;        // void pointer declaration
    int *ip;         // integer pointer declaration
    int marks = 75;  // integer variable
    vp = &marks;     // store address of marks in void pointer
    ip = (int *)vp;  // explicit typecast needed in C++
    cout << "The value of *ip : " << *ip << endl;
    return 0;
}
Explanation: 1. Declare a void pointer vp and an integer pointer ip. 2. Create an int variable marks = 75. 3. Assign vp = &marks; a void pointer can hold the address of any data type. 4. In C++, assigning a void pointer to a typed pointer requires an explicit cast, so write ip = (int *)vp;. 5. Dereference ip with *ip to get 75 and print it. 6. Output: The value of *ip : 75.
Q92.Easy
Write a C++ program that reads a person's name (a single word) from the user and prints the greeting 'Namaste, <name>! Welcome to C++' on the screen.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main() {
    string name;
    cout << "Enter your name: ";
    cin >> name;
    cout << "Namaste, " << name << "! Welcome to C++";
    return 0;
}
Explanation: 1) Include the iostream header so cin and cout are available. 2) Declare a string variable name. 3) Use cin >> name to read one word typed by the user. 4) Use cout to print the greeting with the name inserted in the middle. 5) Return 0 to end the program successfully.
Q93.Easy
Write a C++ program that asks the user for the number of marks to store, dynamically allocates an int array of that size using new, reads the marks into the array, prints them separated by commas, and finally frees the array memory using delete[].
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main()
{
    int n;
    cout << "Enter the number of marks: ";
    cin >> n;
    int *marks = new int[n];
    cout << "Enter the marks: ";
    for (int i = 0; i < n; i++)
        cin >> marks[i];
    cout << "The marks you entered are: ";
    for (int i = 0; i < n; i++)
        cout << marks[i] << ",";
    delete[] marks;
    return 0;
}
Explanation: 1) Read the array size n from the user. 2) Allocate memory with new int[n] and store the address in pointer marks. 3) Use a for loop to read n marks into marks[i]. 4) Use another for loop to print each mark followed by a comma. 5) Free the whole array with delete[] marks (the [] is needed because memory was allocated with new[]). 6) Return 0.
Q94.Easy
Write a C++ program using a while loop that prints the numbers 1 to 10, each on a new line.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main() {
    int i = 1;
    while(i <= 10)
    {
        cout << i << "\n";
        i++;
    }
    return 0;
}
Explanation: 1. Include iostream and use the std namespace. 2. Declare int i = 1 as the starting value. 3. The while condition i <= 10 is checked before each iteration; it is true for i = 1 to 10. 4. Inside the loop, print i followed by a newline, then increment i by 1 with i++. 5. When i becomes 11 the condition i <= 10 is false, so the loop stops after printing 1 through 10.
Q95.Easy
Write a C++ program that creates an infinite while loop by passing true as the test condition, and inside the loop prints the message "Keep Learning C++" each time.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main() {
    while(true)
    {
        cout << "Keep Learning C++" << endl;
    }
    return 0;
}
Explanation: 1. Include the iostream header and use the std namespace so cout is available. 2. In main(), write while(true) — the condition is always true, so the loop never ends on its own. 3. Inside the loop body, print the message "Keep Learning C++" with cout and endl. 4. Because the condition never becomes false, the message keeps printing forever (an infinite loop).
Q96.Easy
Write a C++ program to print the following pattern using cout statements:

Sample Output:
  *****
 *     *
 *     *
 *     *
*       *
 *     *
 *     *
 *     *
  *****
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

int main() {
    cout << "  *****" << endl;
    cout << " *     *" << endl;
    cout << " *     *" << endl;
    cout << " *     *" << endl;
    cout << "*       *" << endl;
    cout << " *     *" << endl;
    cout << " *     *" << endl;
    cout << " *     *" << endl;
    cout << "  *****" << endl;
    return 0;
}
Explanation: 1. The pattern is a diamond-like shape made of asterisks and spaces. 2. The first line has two spaces, then five asterisks. 3. The next three lines have one space, an asterisk, five spaces, and an asterisk. 4. The fifth line has an asterisk, seven spaces, and an asterisk. 5. The next three lines repeat the pattern of lines 2-4. 6. The last line is identical to the first line. 7. Each line is printed using cout with the exact string, followed by endl.
Q97.Easy
Write a C++ program that reads the number of passengers n waiting to buy tickets at a railway booking counter and prints the number of different ways they can stand in a single queue. If n is negative, print an error message.
Show answer & explanation
Answer:
#include <iostream>

unsigned long long arrangements(int n) {
    if (n <= 1)
        return 1;
    return n * arrangements(n - 1);
}

int main() {
    int n;
    std::cout << "Enter the number of passengers: ";
    std::cin >> n;
    if (n < 0) {
        std::cout << "Invalid input: number of passengers cannot be negative." << std::endl;
        return 1;
    }
    unsigned long long ways = arrangements(n);
    std::cout << "Number of ways passengers can queue up: " << ways << std::endl;
    return 0;
}
Explanation: 1) The number of ways to arrange n distinct people in a queue is n! (n factorial). 2) The recursive function arrangements(n) returns 1 when n <= 1 (base case) and otherwise returns n * arrangements(n-1). 3) main() reads n from the user. 4) If n is negative, an error message is printed and the program exits. 5) Otherwise the factorial is computed and printed as the number of possible queues.
Q98.Easy
Write a C++ program that reads an integer N (runs scored by a batsman) and prints the number of ways the batsman can score exactly N runs using only boundaries worth 4 runs and 6 runs (order of shots does not matter). For example, 18 runs can be made as 6+6+6 or 6+4+4+4, so the answer is 2.
Show answer & explanation
Answer:
#include <iostream>

int countWays(int n) {
    int ways = 0;
    for (int fours = 0; 4 * fours <= n; fours++) {
        int remaining = n - 4 * fours;
        if (remaining % 6 == 0) {
            ways++;
        }
    }
    return ways;
}

int main() {
    int n;
    std::cout << "Enter the number of runs (n): ";
    std::cin >> n;
    int ways = countWays(n);
    std::cout << "Number of ways a batsman can score " << n
              << " runs with fours and sixes only: " << ways << std::endl;
    return 0;
}
Explanation: 1) Read N. 2) Loop over the possible number of fours, from 0 up to N/4 (condition 4*fours <= N). 3) For each count of fours, the runs left are N - 4*fours. 4) If that remainder is divisible by 6, the sixes count is fixed, so it is one valid way; increment the counter. 5) Print the counter. Example: N=18 gives fours=0 (three sixes) and fours=3 (remainder 6), so 2 ways.
Q99.Easy
Write a C++ program: A simple encoding scheme converts an even-length binary string into a sequence of letters. Scanning the string from left to right, each pair of bits is replaced as follows: 00 → X, 01 → Y, 10 → Z, 11 → W. Given a binary string S of even length N, print the encoded sequence. For example, if S = "101100", the output should be "ZWX".
Show answer & explanation
Answer:
#include <iostream>
#include <string>

std::string encode(const std::string& S) {
    std::string result = "";
    for (size_t i = 0; i + 1 < S.length(); i += 2) {
        std::string pair = S.substr(i, 2);
        if (pair == "00") result += 'X';
        else if (pair == "01") result += 'Y';
        else if (pair == "10") result += 'Z';
        else if (pair == "11") result += 'W';
    }
    return result;
}

int main() {
    std::string S;
    std::cin >> S;
    std::cout << encode(S) << std::endl;
    return 0;
}
Explanation: 1) Read the binary string S (length is even). 2) Loop i from 0, stepping by 2, so each iteration grabs the pair S[i..i+1]. 3) Map the pair: 00→X, 01→Y, 10→Z, 11→W, and append the letter to the result. 4) For S = "101100": pairs are "10"→Z, "11"→W, "00"→X, giving "ZWX". 5) Print the encoded sequence.
Q100.Easy
Write a C++ program: Cricket Series Prize. A cricket series has 10 matches. Each match can be won by Team A, won by Team B, or end in a tie. The winner of a match gets 3 points, and the loser gets 0 points. In case of a tie, both teams get 1 point each. The total prize pool is 200 * X. After all 10 matches, if one team has strictly more points than the other, that team is declared the champion and gets 70 * X as prize money, and the other team gets 30 * X. If the points are tied, the defending champion Team A is declared the winner, but the winner gets only 50 * X, and the loser gets 50 * X. Given the results of all 10 matches as a string of length 10 consisting of characters 'A' (win by Team A), 'B' (win by Team B), and 'T' (tie), output the prize money that Team A receives.
Show answer & explanation
Answer:
#include <iostream>
#include <string>
using namespace std;

int main() {
    string results;
    cout << "Enter the results of the 10 matches (A, B, or T): ";
    cin >> results;
    int pointsA = 0, pointsB = 0;
    for (char r : results) {
        if (r == 'A') pointsA += 3;
        else if (r == 'B') pointsB += 3;
        else if (r == 'T') { pointsA += 1; pointsB += 1; }
    }
    int X;
    cout << "Enter the value of X: ";
    cin >> X;
    int prizeA;
    if (pointsA > pointsB) prizeA = 70 * X;
    else if (pointsA < pointsB) prizeA = 30 * X;
    else prizeA = 50 * X;
    cout << "Prize money for Team A: " << prizeA << endl;
    return 0;
}
Explanation: 1. Read the results string of length 10 and the value X. 2. Initialize pointsA and pointsB to 0. 3. For each character: if 'A', add 3 to pointsA; if 'B', add 3 to pointsB; if 'T', add 1 to both. 4. Compare pointsA and pointsB: if pointsA > pointsB, Team A gets 70*X; if pointsA < pointsB, Team A gets 30*X; if equal, Team A gets 50*X. 5. Output the prize money for Team A.
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