Question Bank › Technical › C++ › Coding Questions
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.
#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;
}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.
#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;
}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.
#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;
}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.
#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;
}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).#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;
}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.
#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;
}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.
#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;
}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.
#include <iostream>
using namespace std;
int main()
{
int marks = 25;
int &score = marks;
std::cout << score << std::endl;
return 0;
}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.
#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;
}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.
#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;
}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.
#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;
}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.
#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;
}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.
#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;
}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.
#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;
}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.
#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;
}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."
#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;
}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.
#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;
}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.
#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;
}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.
#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;
}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.
#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;
}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.
#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;
}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".
#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;
}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.
#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;
}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.
#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;
}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.
#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;
}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.
#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;
}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.
#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;
}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.
#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;
}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.
#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;
}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.
#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;
}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>
#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;
}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`.
#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;
}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.
#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;
}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.
#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;
}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.
#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;
}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.
#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;
}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.#include <iostream>
using namespace std;
int main()
{
int arr[5] = {4, 0, 7, 0, 9};
for (int i : arr)
{
cout << i << "\n";
}
return 0;
}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}.#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;
}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.#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;
}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.
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 7) {
break;
}
cout << i << "\n";
}
return 0;
}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".
#include <iostream>
using namespace std;
int main() {
char ary[] = "Welcome to C++ tutorial";
cout << "Value of ary is: " << ary << endl;
return 0;
}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
#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;
}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.
#include <iostream>
using namespace std;
int main() {
cout << "Welcome to C++" << endl;
cout << "Learning is fun" << endl;
cout << "End of output" << endl;
return 0;
}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?
#include <iostream>
using namespace std;
int main() {
cout << "Hello, India!" << endl;
return 0;
}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?
#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;
}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.
#include <iostream>
using namespace std;
int main() {
int score = 42; // score holds the player's points
cout << score << "\n";
return 0;
}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.
#include <iostream>
using namespace std;
int main()
{
/* declare and
print variable in C++. */
int marks = 48;
cout << marks << "\n";
return 0;
}Write a C++ program that prints the numbers 1 to 12, but skips printing the number 7 using the continue statement.
#include <iostream>
using namespace std;
int main()
{
for(int i = 1; i <= 12; i++){
if(i == 7){
continue;
}
cout << i << "\n";
}
return 0;
}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.
#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;
}Write a C++ program that uses a do-while loop to print the numbers from 1 to 5, each on a new line.
#include <iostream>
using namespace std;
int main() {
int i = 1;
do {
cout << i << "\n";
i++;
} while (i <= 5);
return 0;
}Write a C++ program that uses an infinite do-while loop (condition true) to repeatedly print the message "Endless do-while Loop".
#include <iostream>
using namespace std;
int main() {
do {
cout << "Endless do-while Loop";
} while (true);
}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.
#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;
}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'.
#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;
}Write a C++ program that declares an integer variable, assigns it the value of a constant expression (7/2) + 3, and prints the result.
#include <iostream>
using namespace std;
int main()
{
int marks;
marks = (7/2) + 3;
cout << "Value of marks is : " << marks;
return 0;
}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>
#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;
}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>
#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;
}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?#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;
}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.
#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;
}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.
#include <iostream>
using namespace std;
int main()
{
int price = 3;
int cost = 8;
int tax = 5;
cout << ((price > cost) || (price > tax));
return 0;
}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.
#include <iostream>
using namespace std;
int main()
{
int marks = 9; // variable declaration
std::cout << (marks >> 2) << std::endl;
return 0;
}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.
#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;
}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.
#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;
}Write a C++ program that uses a for loop to print the numbers from 1 to 5, each on a new line.
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
cout << i << "\n";
}
return 0;
}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.
#include <iostream>
using namespace std;
int main() {
for (;;) {
cout << "Looping forever" << endl;
}
return 0;
}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().
#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;
}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>
#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;
}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
#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;
}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.
#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;
}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.
#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;
}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.
#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;
}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.
#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;
}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.
#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;
}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.
#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;
}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().
#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;
}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.
#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;
}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.
#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;
}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.
#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;
}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.
#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;
}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.#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;
}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.
#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;
}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).
#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;
}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.
#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;
}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.#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;
}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.#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";
}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).
#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;
}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.
#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;
}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.)
#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;
}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.
#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;
}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().
#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;
}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.
#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;
}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.
#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;
}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.
#include <iostream>
using namespace std;
int main() {
string name;
cout << "Enter your name: ";
cin >> name;
cout << "Namaste, " << name << "! Welcome to C++";
return 0;
}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[].
#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;
}Write a C++ program using a while loop that prints the numbers 1 to 10, each on a new line.
#include <iostream>
using namespace std;
int main() {
int i = 1;
while(i <= 10)
{
cout << i << "\n";
i++;
}
return 0;
}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.
#include <iostream>
using namespace std;
int main() {
while(true)
{
cout << "Keep Learning C++" << endl;
}
return 0;
}Write a C++ program to print the following pattern using cout statements: Sample Output: ***** * * * * * * * * * * * * * * *****
#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;
}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.
#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;
}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.
#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;
}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".
#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;
}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.
#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;
}INTMAT EDTECH (OPC) PRIVATE LIMITED
No - 16, Javaraiahna Doddi, Mysore Road,
Bengaluru Urban, BENGALURU,
Karnataka 560098, India
contact@intmatedtech.com