Question Bank › Technical › C++ › Coding Questions
Write a C++ function named `shortenName` that takes a string and returns it trimmed to at most 12 characters. If the string is longer than 12 characters, return only the first 12 characters; otherwise return the string unchanged.
#include <iostream>
#include <string>
using namespace std;
string shortenName(const string& s) {
if (s.length() > 12)
return s.substr(0, 12);
return s;
}
int main() {
cout << shortenName("Rajarajeswari") << endl; // Rajarajeswar
cout << shortenName("Amit") << endl; // Amit
return 0;
}Write a C++ program that reads an array of integers and counts how many entries appear more than once (duplicate entries). For example, for the array {4, 7, 4, 9, 7, 4, 2}, the values 4 and 7 are duplicated, so the count of duplicate values is 2.#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
int main() {
vector<int> arr = {4, 7, 4, 9, 7, 4, 2};
unordered_map<int, int> freq;
for (int x : arr) freq[x]++;
int dupCount = 0;
for (auto &p : freq) {
if (p.second > 1) dupCount++;
}
cout << dupCount << endl;
return 0;
}Write a C++ program to move all zeros in an array to the beginning while maintaining the relative order of the non-zero elements. For example, if the input array is {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0}, the output should be {0, 0, 0, 0, 1, 9, 8, 4, 2, 7, 6}.#include <iostream>
#include <vector>
using namespace std;
void moveZerosToFront(vector<int>& arr) {
int n = arr.size();
int index = n - 1;
// Copy non-zero elements to the back, preserving order
for (int i = n - 1; i >= 0; i--)
if (arr[i] != 0)
arr[index--] = arr[i];
// Fill the rest with zeros
while (index >= 0)
arr[index--] = 0;
}
int main() {
vector<int> arr = {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0};
moveZerosToFront(arr);
cout << "Array after moving zeros to front: ";
for (int num : arr)
cout << num << " ";
cout << endl;
return 0;
}Write a C++ program that dynamically allocates memory for a single integer using the new operator, stores the value 45 in it, prints the value, then releases the memory using the delete operator.
#include <iostream>
using namespace std;
int main()
{
int *ptr;
ptr = new int;
*ptr = 45;
cout << "The value of p is : " << *ptr << endl;
delete ptr;
return 0;
}Write a C++ program that stores the integer 27 in a variable and uses an if statement to check whether it is an odd number. If it is odd, print the message "It is odd number".
#include <iostream>
using namespace std;
int main() {
int num = 27;
if (num % 2 != 0)
{
cout << "It is odd number";
}
return 0;
}Write a C++ program that stores the integer 17 in a variable and uses an if-else statement to print "17 is even" if the number is even, otherwise print "17 is odd".
#include <iostream>
using namespace std;
int main() {
int num = 17;
if (num % 2 == 0) {
cout << "17 is even";
} else {
cout << "17 is odd";
}
return 0;
}Write a C++ program that asks the user to enter an integer (for example, a student's roll number) and then uses an if-else statement to print "Roll number is even" if the number is even, otherwise print "Roll number is odd".
#include <iostream>
using namespace std;
int main() {
int roll;
cout << "Enter roll number: ";
cin >> roll;
if (roll % 2 == 0) {
cout << "Roll number is even" << endl;
} else {
cout << "Roll number is odd" << endl;
}
return 0;
}Write a C++ program that reads a student's marks (an integer) and prints the grade using an if-else-if ladder according to these rules: marks below 0 or above 100 -> print "invalid marks"; 0 to 39 -> "Fail"; 40 to 54 -> "D Grade"; 55 to 69 -> "C Grade"; 70 to 84 -> "B Grade"; 85 to 94 -> "A Grade"; 95 to 100 -> "A+ Grade".
#include <iostream>
using namespace std;
int main()
{
int marks;
cout << "Enter marks to check grade: ";
cin >> marks;
if (marks < 0 || marks > 100)
{
cout << "invalid marks";
}
else if (marks >= 0 && marks < 40)
{
cout << "Fail";
}
else if (marks >= 40 && marks < 55)
{
cout << "D Grade";
}
else if (marks >= 55 && marks < 70)
{
cout << "C Grade";
}
else if (marks >= 70 && marks < 85)
{
cout << "B Grade";
}
else if (marks >= 85 && marks < 95)
{
cout << "A Grade";
}
else if (marks >= 95 && marks <= 100)
{
cout << "A+ Grade";
}
return 0;
}Write a C++ program that declares an integer pointer, allocates memory for one integer at runtime using the new operator, asks the user to enter a number, stores it in that heap memory, and then prints the entered number. Finally, release the allocated memory using delete.
#include <iostream>
using namespace std;
int main()
{
int *marks; // integer pointer variable declaration
marks = new int; // allocating memory on the heap for one integer
cout << "Enter the marks : " << endl;
cin >> *marks;
cout << "Marks entered are " << *marks << endl;
delete marks; // releasing the allocated memory
marks = NULL;
return 0;
}Write a C++ program that defines a namespace called 'MathOps' containing a variable 'pi' (value 3.14159) and a function 'areaOfCircle' that takes a double radius and returns the area (pi * radius * radius). In the main function, read a radius from the user, then using the 'using' directive for the MathOps namespace, print the area of the circle. Also, demonstrate accessing the variable 'pi' directly after the using directive.
#include <iostream>
namespace MathOps {
double pi = 3.14159;
double areaOfCircle(double r) {
return pi * r * r;
}
}
int main() {
double radius;
std::cout << "Enter radius: ";
std::cin >> radius;
using namespace MathOps;
std::cout << "Area of circle: " << areaOfCircle(radius) << std::endl;
std::cout << "Value of pi: " << pi << std::endl;
return 0;
}Write a C++ program that uses the sizeof operator to display the size in bytes of the following data types: int, float, double, and char. Print each size with a descriptive message.
#include <iostream>
using namespace std;
int main() {
cout << "Size of int: " << sizeof(int) << " bytes" << endl;
cout << "Size of float: " << sizeof(float) << " bytes" << endl;
cout << "Size of double: " << sizeof(double) << " bytes" << endl;
cout << "Size of char: " << sizeof(char) << " bytes" << endl;
return 0;
}Write a C++ program that asks the user to enter a number and then uses a switch statement to print a message based on the number. If the number is 5, print "It is 5"; if 15, print "It is 15"; if 25, print "It is 25"; otherwise, print "Not 5, 15 or 25".
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
switch (num) {
case 5:
cout << "It is 5";
break;
case 15:
cout << "It is 15";
break;
case 25:
cout << "It is 25";
break;
default:
cout << "Not 5, 15 or 25";
break;
}
return 0;
}Write a C++ program that demonstrates a virtual function: define a base class Shape with a virtual function show(), and a derived class Circle that overrides show(). In main(), create a Circle object, store its address in a Shape pointer, and call show() through the pointer so that the derived version is invoked at runtime.
#include <iostream>
using namespace std;
class Shape {
public:
virtual void show() {
cout << "Shape class is invoked" << endl;
}
};
class Circle : public Shape {
public:
void show() override {
cout << "Circle class is invoked" << endl;
}
};
int main() {
Shape* s; // pointer of base class
Circle c; // object of derived class
s = &c;
s->show(); // late binding occurs
return 0;
}Write a C++ program that stores the integers 10, 20, 30, 40, 50 in a vector. Using a normal iterator, print all elements in forward order separated by spaces. Then, using a reverse_iterator, print all elements in reverse order separated by spaces. Each list should be on its own line.
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
int main()
{
vector<int> v{10,20,30,40,50};
vector<int>::iterator itr;
vector<int>::reverse_iterator ritr;
for(itr = v.begin(); itr != v.end(); itr++)
{
cout<<*itr<<" ";
}
cout<<'\n';
for(ritr = v.rbegin(); ritr != v.rend(); ritr++)
{
cout<<*ritr<<" ";
}
cout<<'\n';
return 0;
}Write a C++ program that defines a class named 'Student' with a user-defined copy constructor. The class should have a data member 'roll' (integer). Include a parameterized constructor to initialize 'roll', and a copy constructor that copies the roll number from another Student object. In main(), create a Student object s1 with roll number 101, then create a copy s2 using the copy constructor, and display the roll numbers of both objects.
#include <iostream>
using namespace std;
class Student {
int roll;
public:
Student(int r) {
roll = r;
}
Student(const Student &s) {
roll = s.roll;
}
void display() {
cout << "Roll number: " << roll << endl;
}
};
int main() {
Student s1(101);
Student s2(s1);
cout << "s1: ";
s1.display();
cout << "s2: ";
s2.display();
return 0;
}Write a C++ program to demonstrate shallow copy. The default copy constructor produces a shallow copy, which copies all member variables as they are, including pointers, so the source and copy share the same memory. Use a class named 'Employee' with integer members 'id' and 'salary', and an integer pointer 'bonus'. In main, create an object e1, set its data to id=101, salary=50000, and *bonus=5000. Then create a copy e2 using the default copy constructor, and display the values of e2.
#include <iostream>
using namespace std;
class Employee {
int id;
int salary;
int *bonus;
public:
Employee() {
bonus = new int;
}
void setData(int i, int s, int b) {
id = i;
salary = s;
*bonus = b;
}
void showData() {
cout << "ID: " << id << endl;
cout << "Salary: " << salary << endl;
cout << "Bonus: " << *bonus << endl;
}
};
int main() {
Employee e1;
e1.setData(101, 50000, 5000);
Employee e2 = e1;
e2.showData();
return 0;
}Write a C++ program to demonstrate deep copy. Deep copy dynamically allocates memory for the copy and copies the actual value, so the source and copy have distinct memory locations. This requires a user-defined copy constructor. Use a class named 'Student' with integer members 'roll' and 'marks', and an integer pointer 'ptr'. In main, create an object s1, set its data to roll=10, marks=85, and *ptr=95. Then create a copy s2 using the copy constructor, and display the values of s2.
#include <iostream>
using namespace std;
class Student {
public:
int roll;
int marks;
int *ptr;
Student() {
ptr = new int;
}
Student(const Student &s) {
roll = s.roll;
marks = s.marks;
ptr = new int;
*ptr = *(s.ptr);
}
void setData(int r, int m, int p) {
roll = r;
marks = m;
*ptr = p;
}
void showData() {
cout << "Roll: " << roll << endl;
cout << "Marks: " << marks << endl;
cout << "Pointer value: " << *ptr << endl;
}
};
int main() {
Student s1;
s1.setData(10, 85, 95);
Student s2 = s1;
s2.showData();
return 0;
}Write a C++ program that creates two vectors v1 = {1,2,3,4,5} and v2 = {3,4,5,6,7}. Using an insert_iterator (inserter) positioned at the 4th element of v1 (i.e., after advancing the iterator by 3 from v1.begin()), copy all elements of v2 into v1. Then print all elements of v1 separated by spaces.#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> v1, v2;
for (int i = 1; i <= 5; i++) {
v1.push_back(i);
v2.push_back(i + 2);
}
vector<int>::iterator it = v1.begin();
advance(it, 3);
copy(v2.begin(), v2.end(), inserter(v1, it));
cout << "Elements of v1 are :";
for (it = v1.begin(); it != v1.end(); ++it)
cout << ' ' << *it;
cout << '\n';
return 0;
}Write a C++ program that uses an ostream_iterator to print the elements of a vector of integers separated by a comma and a space, using the standard output stream (cout). The vector should contain the values 10, 20, 30, 40, 50. Use the copy algorithm together with ostream_iterator so that the output is: 10, 20, 30, 40, 50
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> nums;
for (int i = 1; i <= 5; i++)
nums.push_back(i * 10);
ostream_iterator<int> out(cout, ", ");
copy(nums.begin(), nums.end() - 1, out);
cout << nums.back() << endl;
return 0;
}Write a C++ program that demonstrates aggregation. Create a class `Home` with data members `line`, `area`, `city` and a constructor. Create a class `Student` that HAS-A `Home` (stores a pointer to a `Home` object) along with its own `rollNo` and `name`. The `Student` constructor should take the roll number, name and a `Home*`. Add a `show()` method that prints the roll number, name, home line, area and city separated by spaces. In `main`, create a `Home` object with line "12, MG Road", area "Pune", city "MH", then a `Student` with roll 205 and name "Rohan" using that home, and call `show()`.
#include <iostream>
using namespace std;
class Home {
public:
string line, area, city;
Home(string line, string area, string city)
{
this->line = line;
this->area = area;
this->city = city;
}
};
class Student
{
private:
Home* home; // Student HAS-A Home
public:
int rollNo;
string name;
Student(int rollNo, string name, Home* home)
{
this->rollNo = rollNo;
this->name = name;
this->home = home;
}
void show()
{
cout << rollNo << " " << name << " " <<
home->line << " " << home->area << " " << home->city << endl;
}
};
int main(void) {
Home h1 = Home("12, MG Road", "Pune", "MH");
Student s1 = Student(205, "Rohan", &h1);
s1.show();
return 0;
}Write a C++ program that demonstrates how the break statement inside an inner loop only exits the inner loop. Use nested for loops: the outer loop runs for i from 1 to 3, and the inner loop runs for j from 1 to 3. Inside the inner loop, if i equals 2 and j equals 2, execute a break statement. Otherwise, print the values of i and j separated by a space, followed by a newline. What is the output of the program?
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
break;
}
cout << i << " " << j << "\n";
}
}
return 0;
}Write a C++ program that demonstrates call by reference by swapping two integers. Declare two integer variables a = 15 and b = 8 in main. Write a function swapRef that takes two integer pointers and swaps the values they point to. Call swapRef with the addresses of a and b. After the call, print the values of a and b each on a new line.
#include <iostream>
using namespace std;
void swapRef(int *p, int *q) {
int temp = *p;
*p = *q;
*q = temp;
}
int main() {
int a = 15, b = 8;
swapRef(&a, &b);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}Write a C++ program that demonstrates data abstraction: create a class 'WaterPump' with private data members (speed level and mode) and public member functions to switch the pump ON/OFF, set the speed, set the mode, and display the current status. The private members must not be accessible directly from main(). Use the class in main() to switch the pump on, set speed to 2, set mode to 1, and print the status.
#include <iostream>
using namespace std;
class WaterPump {
private:
bool isOn;
int speed;
int mode;
public:
WaterPump() {
isOn = false;
speed = 0;
mode = 0;
}
void switchOn() { isOn = true; }
void switchOff() { isOn = false; }
void setSpeed(int s) { if (isOn) speed = s; }
void setMode(int m) { if (isOn) mode = m; }
void showStatus() {
cout << "Pump is " << (isOn ? "ON" : "OFF") << endl;
cout << "Speed level: " << speed << endl;
cout << "Mode: " << mode << endl;
}
};
int main() {
WaterPump p;
p.switchOn();
p.setSpeed(2);
p.setMode(1);
p.showStatus();
return 0;
}Write a C++ program that demonstrates passing a function pointer as a parameter to another function. Define two functions: 'greet' that prints "Hello from greet" and 'execute' that takes a function pointer as a parameter and calls the function it points to. In main, call 'execute' with 'greet' as the argument.
#include <iostream>
using namespace std;
void greet() {
cout << "Hello from greet" << endl;
}
void execute(void (*funcPtr)()) {
funcPtr();
}
int main() {
execute(greet);
return 0;
}Write a C++ program that demonstrates ambiguity resolution in multiple inheritance. Create a base class 'X' with a public method 'show()' that prints "Class X". Create another base class 'Y' with a public method 'show()' that prints "Class Y". Derive a class 'Z' from both 'X' and 'Y' using multiple inheritance. In 'Z', define a method 'display()' that calls 'show()' from both base classes explicitly using the scope resolution operator. In the main function, create an object of 'Z' and call 'display()'.
#include <iostream>
using namespace std;
class X {
public:
void show() {
cout << "Class X" << endl;
}
};
class Y {
public:
void show() {
cout << "Class Y" << endl;
}
};
class Z : public X, public Y {
public:
void display() {
X::show();
Y::show();
}
};
int main() {
Z z;
z.display();
return 0;
}Write a C++ program that demonstrates hybrid inheritance. Create a base class 'Person' with a protected integer 'age' and a public method 'getAge()' to input the age. Derive a class 'Student' from 'Person' that adds a protected integer 'rollNo' and a public method 'getRollNo()' to input the roll number. Derive another class 'Employee' from 'Person' that adds a protected integer 'empId' and a public method 'getEmpId()' to input the employee ID. Finally, create a class 'Intern' that inherits from both 'Student' and 'Employee', and has a public method 'display()' that prints the age, roll number, and employee ID. In the main function, create an object of 'Intern', call the input methods, and then call 'display()'.
#include <iostream>
using namespace std;
class Person {
protected:
int age;
public:
void getAge() {
cout << "Enter age: ";
cin >> age;
}
};
class Student : virtual public Person {
protected:
int rollNo;
public:
void getRollNo() {
cout << "Enter roll number: ";
cin >> rollNo;
}
};
class Employee : virtual public Person {
protected:
int empId;
public:
void getEmpId() {
cout << "Enter employee ID: ";
cin >> empId;
}
};
class Intern : public Student, public Employee {
public:
void display() {
cout << "Age: " << age << endl;
cout << "Roll No: " << rollNo << endl;
cout << "Employee ID: " << empId << endl;
}
};
int main() {
Intern intern;
intern.getAge();
intern.getRollNo();
intern.getEmpId();
intern.display();
return 0;
}Write a C++ program that demonstrates an abstract class. Create an abstract base class named Vehicle that has a pure virtual function called start(). Derive two classes from it: Bike and Truck. Each derived class must provide its own implementation of start() that prints "bike starts with kick..." and "truck starts with ignition..." respectively. In main(), create one object of each derived class and call start() on both.
#include <iostream>
using namespace std;
class Vehicle
{
public:
virtual void start() = 0;
};
class Bike : public Vehicle
{
public:
void start()
{
cout << "bike starts with kick..." << endl;
}
};
class Truck : public Vehicle
{
public:
void start()
{
cout << "truck starts with ignition..." << endl;
}
};
int main()
{
Bike b;
Truck t;
b.start();
t.start();
return 0;
}Write a C++ program that defines a class Counter with a private integer member count initialised to 5. Overload the unary prefix ++ operator so that it increases count by 3, and provide a member function show() that prints the count. In main, create a Counter object, apply ++ to it, and display the result.
#include <iostream>
using namespace std;
class Counter
{
private:
int count;
public:
Counter() : count(5) {}
void operator++()
{
count = count + 3;
}
void show()
{
cout << "The Count is: " << count;
}
};
int main()
{
Counter c;
++c;
c.show();
return 0;
}Write a C++ program that demonstrates call-by-value, call-by-reference with a pointer argument, and call-by-reference with a reference argument. The program should define three functions: one that takes an int by value and returns its square, one that takes an int* and squares the pointed-to value in place, and one that takes an int& and squares the referenced value in place. In main, declare three integer variables initialized to 5, call each function appropriately, and print the results to show that call-by-value does not modify the original variable while the other two do.
#include <iostream>
using namespace std;
int squareByValue(int n) {
n *= n;
return n;
}
void squareByPointer(int* n) {
*n *= *n;
}
void squareByReference(int& n) {
n *= n;
}
int main() {
int a = 5, b = 5, c = 5;
cout << "Call-by-Value:" << endl;
cout << "Before: a = " << a << endl;
int result = squareByValue(a);
cout << "Square returned: " << result << endl;
cout << "After: a = " << a << " (unchanged)" << endl;
cout << "\nCall-by-Reference with Pointer:" << endl;
cout << "Before: b = " << b << endl;
squareByPointer(&b);
cout << "After: b = " << b << " (changed)" << endl;
cout << "\nCall-by-Reference with Reference:" << endl;
cout << "Before: c = " << c << endl;
squareByReference(c);
cout << "After: c = " << c << " (changed)" << endl;
return 0;
}Write a C++ program that demonstrates run-time polymorphism using a base class 'Vehicle' with a virtual function 'move()', and two derived classes 'Car' and 'Bike' that each override 'move()'. In main, create objects of both derived classes and call 'move()' through a base-class pointer to show which version runs.
#include <iostream>
using namespace std;
class Vehicle { // base class
public:
virtual void move() { // virtual function
cout << "Vehicle is moving..." << endl;
}
};
class Car : public Vehicle {
public:
void move() override {
cout << "Car is driving on the road..." << endl;
}
};
class Bike : public Vehicle {
public:
void move() override {
cout << "Bike is riding on the street..." << endl;
}
};
int main() {
Vehicle* v;
Car c;
Bike b;
v = &c;
v->move(); // calls Car::move()
v = &b;
v->move(); // calls Bike::move()
return 0;
}Write a C++ program that demonstrates runtime polymorphism with data members. Create a base class 'Shape' with a data member 'color' initialized to "Red". Derive a class 'Circle' from 'Shape' that hides the 'color' member with its own 'color' initialized to "Blue". In the main function, create an object of 'Circle' and use a 'Shape' reference to it. Print the 'color' using the reference and also print the 'color' using the 'Circle' object directly. Explain why the outputs differ.
#include <iostream>
#include <string>
using namespace std;
class Shape {
public:
string color = "Red";
};
class Circle : public Shape {
public:
string color = "Blue";
};
int main() {
Circle c;
Shape &ref = c; // reference to base class
cout << "Color via Shape reference: " << ref.color << endl;
cout << "Color via Circle object: " << c.color << endl;
return 0;
}Write a C++ program that demonstrates pass-by-reference. In main, declare an integer variable 'total' with value 40 and print it. Then call a function 'update' that takes an int reference parameter and sets it to 15. After the call, print the value of 'total' again to show that the original variable was modified.
#include <iostream>
using namespace std;
void update(int &);
int main()
{
int total = 40;
std::cout << "Value of 'total' is :" << total << std::endl;
update(total);
std::cout << "Now value of 'total' is :" << total << std::endl;
return 0;
}
void update(int &m)
{
m = 15;
}Write a C++ program that demonstrates handling the SIGINT signal. Use a global variable of type volatile std::sig_atomic_t to record the signal status. Install a handler for SIGINT with signal(), then call raise(SIGINT) to trigger it. After raise() returns, print the recorded signal status value to the console.
#include <csignal>
#include <iostream>
namespace
{
volatile std::sig_atomic_t gSignalStatus = 0;
}
void signalHandler(int sig)
{
gSignalStatus = sig;
}
int main()
{
signal(SIGINT, signalHandler);
raise(SIGINT);
std::cout << "Signal status: " << gSignalStatus << std::endl;
return 0;
}Write a C++ program that defines a class template named 'Box' with one template parameter 'T'. The class should store a single value of type T and provide a constructor to set it and a member function 'show()' that prints the stored value. In main(), create a Box<int> holding 25 and a Box<string> holding "Namaste", and call show() on both.
#include <iostream>
#include <string>
using namespace std;
template <class T>
class Box {
T value;
public:
Box(T v) { value = v; }
void show() { cout << value << endl; }
};
int main() {
Box<int> b1(25);
Box<string> b2("Namaste");
b1.show();
b2.show();
return 0;
}Write a C++ program that demonstrates a class template with a non-type template argument. Create a template class called FixedBox that takes a type parameter T and an integer non-type parameter cap (the capacity). The class should store an array of T of size cap and provide a method fill(T value) that sets every element to value, and a method total() that returns the sum of all elements. In main(), create a FixedBox<int, 4>, fill it with 7, and print the total.
#include <iostream>
using namespace std;
template <class T, int cap>
class FixedBox {
T arr[cap];
public:
void fill(T value) {
for (int i = 0; i < cap; i++)
arr[i] = value;
}
T total() {
T sum = 0;
for (int i = 0; i < cap; i++)
sum += arr[i];
return sum;
}
};
int main() {
FixedBox<int, 4> box;
box.fill(7);
cout << box.total() << endl;
return 0;
}Write a C++ program to check whether the sequence of numbers in a given array is an "Arithmetic" sequence or a "Geometric" sequence. Return -1 if the sequence is neither "Arithmetic" nor "Geometric". For example, the array {3, 6, 12, 24} is Geometric, {5, 10, 15, 20} is Arithmetic, and {2, 4, 7, 11} is neither.#include <iostream>
#include <vector>
using namespace std;
int classify(vector<int> &a) {
int n = a.size();
if (n < 2) return 1; // trivially both; treat as Arithmetic
bool isArith = true, isGeo = true;
int d = a[1] - a[0];
for (int i = 2; i < n; i++)
if (a[i] - a[i-1] != d) { isArith = false; break; }
if (a[0] == 0) {
isGeo = false;
} else {
// check constant ratio using cross multiplication to avoid fractions
for (int i = 2; i < n; i++)
if ((long long)a[i] * a[i-2] != (long long)a[i-1] * a[i-1]) { isGeo = false; break; }
}
if (isArith) return 1;
if (isGeo) return 2;
return -1;
}
int main() {
vector<int> a1 = {3, 6, 12, 24};
vector<int> a2 = {5, 10, 15, 20};
vector<int> a3 = {2, 4, 7, 11};
cout << classify(a1) << endl; // 2 -> Geometric
cout << classify(a2) << endl; // 1 -> Arithmetic
cout << classify(a3) << endl; // -1 -> neither
return 0;
}Write a C++ program to find the largest sum of a contiguous subarray in a given array of integers. Use Kadane's algorithm. Your program should read an integer n (the number of elements), then n integers, and output the maximum subarray sum. For example, if the input is: 8 -2 1 -3 4 -1 2 1 -5 Then the output should be 6, because the subarray [4, -1, 2, 1] has the largest sum.
#include <iostream>
#include <climits>
using namespace std;
int main() {
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int max_so_far = INT_MIN;
int max_ending_here = 0;
for (int i = 0; i < n; i++) {
max_ending_here += arr[i];
if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
if (max_ending_here < 0)
max_ending_here = 0;
}
cout << max_so_far << endl;
return 0;
}Write a C++ program that reads a count k and prints the sum of the first k prime numbers (for example, if k = 5 the first five primes are 2, 3, 5, 7, 11 and their sum is 28). If k is 0, print nothing.
#include <iostream>
using namespace std;
int main() {
const int LIMIT = 1000000;
const int ROOT = 1000;
int k;
int marked[LIMIT + 1] = {0};
int i, j;
marked[0] = 1;
marked[1] = 1;
cin >> k;
for (i = 4; i <= LIMIT; i += 2)
marked[i] = 1;
for (i = 3; i <= ROOT; i += 2)
for (j = i + i; j <= LIMIT; j += i)
marked[j] = 1;
if (k == 0)
return 0;
long long sum = 0;
int count = 0;
for (i = 2; count < k; i++) {
if (marked[i] == 0) {
count++;
sum += i;
}
}
cout << "Sum of the first " << k << " prime numbers is: " << sum;
return 0;
}Write a C++ program that reads an odd integer m (the order of a matrix) and prints an m×m magic square using the Siamese (De la Loubère) method: place 1 in the middle of the last row, then place each next number one row down and one column right (wrapping around); if that cell is already filled, place the number directly above the previously placed number instead. If m is even, print "Invalid input: Order must be an odd number." and stop.
#include <iostream>
#include <vector>
std::vector<std::vector<int>> buildMagicSquare(int m) {
std::vector<std::vector<int>> grid(m, std::vector<int>(m, 0));
int value = 1;
int r = m - 1; // start at last row
int c = m / 2; // middle column
while (value <= m * m) {
grid[r][c] = value++;
int nr = (r + 1) % m; // one row down, wrapping
int nc = (c + 1) % m; // one column right, wrapping
if (grid[nr][nc] != 0) { // occupied -> go one row up from current cell
nr = (r - 1 + m) % m;
nc = c;
}
r = nr;
c = nc;
}
return grid;
}
int main() {
int m;
std::cout << "Enter the order of the magic square (odd number): ";
std::cin >> m;
if (m % 2 == 0) {
std::cout << "Invalid input: Order must be an odd number." << std::endl;
return 1;
}
std::vector<std::vector<int>> grid = buildMagicSquare(m);
std::cout << "Magic Square of order " << m << ":\n";
for (const auto& row : grid) {
for (int v : row) {
std::cout << v << "\t";
}
std::cout << std::endl;
}
return 0;
}Write a C++ program: Given an n×n chessboard grid, count the total number of rectangles (of any size, including squares) that can be formed using the grid lines. For example, a 2×2 board contains 9 rectangles. Read n from the user and print the total count.
#include <iostream>
int countRectangles(int n) {
int total = 0;
for (int m = 1; m <= n; ++m) {
for (int k = 1; k <= n; ++k) {
total += (n - m + 1) * (n - k + 1);
}
}
return total;
}
int main() {
int n;
std::cout << "Enter the size of the board (n): ";
std::cin >> n;
std::cout << "Total number of rectangles on a " << n << "x" << n << " board: " << countRectangles(n) << std::endl;
return 0;
}Write a C++ program that takes three integer arrays sorted in ascending order and returns the smallest number common to all three arrays. If there is no common number, return -1. The arrays are already sorted, so use three pointers to find the common element efficiently.
#include <iostream>
#include <vector>
using namespace std;
int smallestCommon(const vector<int>& a, const vector<int>& b, const vector<int>& c) {
int i = 0, j = 0, k = 0;
while (i < a.size() && j < b.size() && k < c.size()) {
if (a[i] == b[j] && b[j] == c[k])
return a[i];
if (a[i] <= b[j] && a[i] <= c[k])
i++;
else if (b[j] <= a[i] && b[j] <= c[k])
j++;
else
k++;
}
return -1;
}
int main() {
vector<int> arr1 = {1, 3, 5, 7, 9};
vector<int> arr2 = {2, 3, 6, 7, 10};
vector<int> arr3 = {3, 4, 7, 8, 11};
int result = smallestCommon(arr1, arr2, arr3);
cout << result << endl;
return 0;
}Write a C++ program that displays the current date and time by printing the day, month, year, hour, minute and second separately, using the `<ctime>` library.
#include <iostream>
#include <ctime>
using namespace std;
int main() {
time_t now = time(NULL);
tm* tPtr = localtime(&now);
cout << "Current Date and Time :" << endl;
cout << "------------------------" << endl;
cout << "seconds = " << tPtr->tm_sec << endl;
cout << "minutes = " << tPtr->tm_min << endl;
cout << "hours = " << tPtr->tm_hour << endl;
cout << "day of month = " << tPtr->tm_mday << endl;
cout << "month of year = " << (tPtr->tm_mon) + 1 << endl;
cout << "year = " << (tPtr->tm_year) + 1900 << endl;
cout << "weekday = " << tPtr->tm_wday << endl;
cout << "day of year = " << tPtr->tm_yday << endl;
cout << "daylight savings = " << tPtr->tm_isdst << endl;
cout << "Current Date: " << tPtr->tm_mday << "/" << (tPtr->tm_mon) + 1 << "/" << (tPtr->tm_year) + 1900 << endl;
cout << "Current Time: " << tPtr->tm_hour << ":" << tPtr->tm_min << ":" << tPtr->tm_sec << endl;
return 0;
}Write a C++ program that defines a function reverseK that takes a queue of integers and an integer k, and reverses the first k elements of the queue, leaving the rest of the queue unchanged. The function should modify the queue in place. For example, if the queue contains [10, 20, 30, 40, 50] and k = 3, after reversal the queue should be [30, 20, 10, 40, 50]. Assume k is between 1 and the size of the queue.
#include <iostream>
#include <queue>
#include <stack>
using namespace std;
void reverseK(queue<int>& q, int k) {
if (k <= 1 || q.empty()) return;
stack<int> s;
int n = q.size();
// Push first k elements onto stack
for (int i = 0; i < k; i++) {
s.push(q.front());
q.pop();
}
// Pop from stack and push back to queue
while (!s.empty()) {
q.push(s.top());
s.pop();
}
// Move the remaining elements to the back
for (int i = 0; i < n - k; i++) {
q.push(q.front());
q.pop();
}
}
int main() {
queue<int> q;
q.push(10);
q.push(20);
q.push(30);
q.push(40);
q.push(50);
int k = 3;
reverseK(q, k);
cout << "Queue after reversing first " << k << " elements: ";
while (!q.empty()) {
cout << q.front() << " ";
q.pop();
}
cout << endl;
return 0;
}Write a C++ program that demonstrates the use of free() to release dynamically allocated memory. The program should allocate memory for 4 integers using malloc, read 4 integer values from the user, print them, then call free() on the pointer. After freeing, print a message 'Memory freed' and then attempt to print the values again (which will show garbage or undefined behavior). Use appropriate headers and namespace.
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
int *ptr;
ptr = (int*) malloc(4 * sizeof(int));
if (ptr == NULL) {
cout << "Memory allocation failed" << endl;
return 1;
}
cout << "Enter 4 integers:" << endl;
for (int i = 0; i < 4; i++) {
cin >> ptr[i];
}
cout << "You entered: ";
for (int i = 0; i < 4; i++) {
cout << ptr[i] << " ";
}
cout << endl;
free(ptr);
cout << "Memory freed" << endl;
cout << "Values after free (garbage): ";
for (int i = 0; i < 4; i++) {
cout << ptr[i] << " ";
}
cout << endl;
return 0;
}Write a C++ program that dynamically allocates an array of integers using malloc. The program should ask the user for the number of elements, allocate memory accordingly, then read that many integers into the array, print them, and finally free the memory. Use appropriate typecasting and sizeof operator.
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int *arr = (int*) malloc(n * sizeof(int));
if (arr == nullptr) {
cout << "Memory allocation failed" << endl;
return 1;
}
for (int i = 0; i < n; ++i) {
cout << "Enter element " << i+1 << ": ";
cin >> arr[i];
}
cout << "You entered: ";
for (int i = 0; i < n; ++i) {
cout << arr[i] << " ";
}
cout << endl;
free(arr);
return 0;
}Write a C++ program that shows what happens when the virtual keyword is NOT used: define a base class Vehicle with a non-virtual function describe() printing a value 7, and a derived class Car that defines its own describe() printing a value 12. In main(), assign a Car object's address to a Vehicle pointer and call describe() through the pointer.
#include <iostream>
using namespace std;
class Vehicle {
int x = 7;
public:
void describe() {
cout << "Value of x is : " << x << endl;
}
};
class Car : public Vehicle {
int y = 12;
public:
void describe() {
cout << "Value of y is : " << y << endl;
}
};
int main() {
Vehicle* v;
Car c;
v = &c;
v->describe(); // early binding: base version is called
return 0;
}Write a C++ program that demonstrates a pure virtual function and runtime polymorphism. Create an abstract base class 'Shape' with a pure virtual function 'area()'. Derive two classes 'Rectangle' and 'Circle' from 'Shape', each implementing 'area()'. In main, create a pointer of type Shape* and use it to call area() for objects of both derived classes. Print the area with a suitable message.
#include <iostream>
using namespace std;
class Shape {
public:
virtual void area() = 0; // pure virtual function
};
class Rectangle : public Shape {
double length, width;
public:
Rectangle(double l, double w) : length(l), width(w) {}
void area() override {
cout << "Area of rectangle: " << length * width << endl;
}
};
class Circle : public Shape {
double radius;
public:
Circle(double r) : radius(r) {}
void area() override {
cout << "Area of circle: " << 3.14159 * radius * radius << endl;
}
};
int main() {
Shape* ptr;
Rectangle rect(5.0, 3.0);
Circle circ(2.0);
ptr = ▭
ptr->area();
ptr = ˆ
ptr->area();
return 0;
}INTMAT EDTECH (OPC) PRIVATE LIMITED
No - 16, Javaraiahna Doddi, Mysore Road,
Bengaluru Urban, BENGALURU,
Karnataka 560098, India
contact@intmatedtech.com