0% found this document useful (0 votes)
15 views93 pages

C++ Programming Lab Exercises

The document outlines a series of practical programming exercises in C++ for an OOPS lab course, detailing tasks such as adding numbers, checking even or odd, and implementing classes and objects. Each lab session includes multiple programming tasks with specified submission dates and expected outcomes. The exercises progressively cover basic to advanced concepts in C++, including array handling, function overloading, and exception handling.

Uploaded by

Nisha sharma
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views93 pages

C++ Programming Lab Exercises

The document outlines a series of practical programming exercises in C++ for an OOPS lab course, detailing tasks such as adding numbers, checking even or odd, and implementing classes and objects. Each lab session includes multiple programming tasks with specified submission dates and expected outcomes. The exercises progressively cover basic to advanced concepts in C++, including array handling, function overloading, and exception handling.

Uploaded by

Nisha sharma
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

(BIT-202) OOPS LAB

SUBMITTED TO: SUBMITTED BY:


Dr Dipika Ishanvi Srivastava
(ECE-AI 1)
04801182024
INDEX
SERIAL
PRACTICAL DATE SIGNATURE
NUMBER
Lab 1. 1 Write a program for Adding two numbers 6 Aug 2025
in C++.

2 Write a C++ program to check if a number 6 Aug 2025


is even or odd.

3 Write a program to swap two numbers in 6 Aug 2025


C++.

4 Write a C++ program to find the largest 6 Aug 2025


number among three numbers.
5 Write a C++ Program to Find the sum of all 6 Aug 2025
the natural numbers from 1 to n.

6 Write a program in C++ to check whether 6 Aug 2025


a number is prime or not.

7 Write a program in C++ to check whether 6 Aug 2025


a number is prime or not.

Lab 2.8 Write a program for adding two numbers 13 Aug 2025
in C++ using classes and objects.

9 Write a program to check whether a 13 Aug 2025


number is odd or even in C++ using classes
and objects.
10 Write a program to swap two numbers in 13 Aug 2025
C++ using classes and objects.

11 Write a program to find the largest 13 Aug 2025


number among three numbers in C++
using classes and objects.
12 Write a program to find the sum of all the 13 Aug 2025
natural numbers from 1 to n in C++ using
classes and objects.
13 Write a program to check whether a 13 Aug 2025
number is prime or not in C++ using
classes and objects.
14 Write a program to compute the power a 13 Aug 2025
given number to a given power in C++
using classes and objects.
15 Write a C++ program using class and 13 Aug 2025
object to check whether a given year is a
leap year or not.
16 Write a C++ program using class and 13 Aug 2025
object to accept a coordinate point (x, y)
in the XY coordinate system and
determine in which quadrant the point
lies.
17 Write a C++ program using class and 13 Aug 2025
object to read a student’s Roll Number,
Name, and marks in three subjects.
Calculate the total marks, percentage,
division, and grade of the student, and
display the result.
18 Write a C++ program using class and 13 Aug 2025
object to display the first N terms of odd
natural numbers and their sum.
19 Write a C++ program using class and 13 Aug 2025
object to check whether a given number is
a palindrome or not.
Lab 3.20 Basic Array Input and Output Using Class. 20 Aug 2025
Create a class ArrayHandler that stores an
array of integers. Include methods to Input
n elements into the array and Display the
array elements.
21 Write C++ program to Find Maximum and 20 Aug 2025
Minimum Element in an Array using Class.
22 Write C++ program using class to Sort the 20 Aug 2025
Array in Ascending Order.
23 Write C++ program using class to Search 20 Aug 2025
for an Element in the Array.
24 Write a C++ Program using class that 20 Aug 2025
Count Frequency of Elements in the Array.
Create a method that Counts how many
times each unique element appears in the
array and Displays the frequency.
Lab 4.25 Write a C++ program that defines a 27 Aug 2025
function int square(int num) to return the
square of a given number. In the main()
function, prompt the user to enter an
integer and display its square using the
function.
26 Write a C++ program using an inline 27 Aug 2025
function float area(float radius) to
calculate and return the area of a circle. In
the main() function, take input for the
radius and display the result.
27 Write a C++ program to define a function 27 Aug 2025
float calculateInterest(float principal, float
rate = 5.0, int time = 2) that calculates and
returns simple interest using the formula
SI = (P * R * T) / 100. Call the function with
different combinations of arguments (all,
two, one) to demonstrate default
argument behavior.
28 Write a C++ program to compare the 27 Aug 2025
behavior of function overloading and
default arguments by defining:
 One function int add(int a, int b)
 Another function int add(int a, int
b = 0, int c = 0)
Call the function with different sets of
arguments and explain what happens.
29 Create a C++ program that uses an inline 27 Aug 2025
function int max(int a, int b) to return the
maximum of two numbers. In the main()
function, ask the user for two integers and
print the maximum using the function.
30 Write a C++ program that defines a 27 Aug 2025
function void printDetails(string name, int
age = 18, string city = "Unknown"). In the
main() function, call printDetails():
 with all arguments
 with one or two arguments
Demonstrate how default values are used
for the missing parameters.
Lab 5.31 Create a class BitwiseDemo with two 3 Sept 2025
integers and methods to perform AND,
OR, and XOR.
32 Create a class NumberCheck with a 3 Sept 2025
method isEven(int n) that uses the bitwise
AND operator (n & 1) to check if a number
is even.
33 Create a class Swapper with a method 3 Sept 2025
swap(int a, int b) that swaps two numbers
using the XOR (^) operator, and display the
values before and after swapping.
34 Create a class BitCounter with a method 3 Sept 2025
countOnes(int n) that uses bitwise
operators to count the number of 1s in the
binary representation of a number.
35 Create a class ShiftDemo with methods 3 Sept 2025
multiplyBy2(int n) and divideBy2(int n)
using left shift (<>).
Lab 6.36 Write a program to declare an integer, 10 Sept 2025
store its address in a pointer, and display
both the value and address.
37 Write a program to access elements of an 10 Sept 2025
array using pointers instead of the array
index.
38 Write a function swap(int *a, int *b) that 10 Sept 2025
swaps two numbers using pointers.
39 Write a program to calculate the sum of 10 Sept 2025
elements of an array using pointers.
40 Write a function that takes a pointer to an 10 Sept 2025
integer and increments its value by 1.
Create a class BankAccount with private
Lab 7.41 members accountNumber and balance. 24 Sep 2025
Write public functions to set and display
values.
42 Create a class Student with private
members name and marks. 24 Sep 2025
43 Create a class Counter with a static
variable count. 24 Sep 2025
Create a class MyClass with a private static
44 variable data. 24 Sep 2025
Create class Employee with private
45 members empID, salary, and a static 24 Sep 2025
empCount
Create a base class Person with data
Lab 8.46 members name and age, and a derived
class Student that adds a studentID and a 12 Nov 2025
method to display all details.
Define a base class Employee with
protected members empID and salary.
47 Create a derived class Manager that adds
bonus and a function 12 Nov 2025
calculateTotalSalary() to compute total
pay.
Define a base class Account that stores
48 accountNumber and balance (private). 12 Nov 2025
Provide public functions to set and get
these values. Derive a class
SavingsAccount that adds interestRate and
a function to calculate interest.
Lab9.49 Write a C++ program to create a class
representing a geometric shape with a 19 Nov 2025
constructor that initialises its dimensions.
Implement a destructor to display a
message when an object of the class is
destroyed.
50 Write a C++ program to develop a class for 19 Nov 2025
a simple bank account with a constructor
that initialises its dimensions. Implement a
destructor to display a message when an
object of the class is destroyed.
51 Write a C++ program to construct a class 19 Nov 2025
representing a university course with a
constructor to set course details. Include a
destructor to release any dynamically
allocated memory associated with the
course object.
52 Write a C++ code to construct a class
representing a book with constructor
parameters for its title, author and
publication year. Include a destructor to
release any dynamically allocated memory
for story book details.
53 Design a single C++ program that 19 Nov 2025
illustrating single inheritance, multiple
inheritance, multilevel inheritance.
54 Design a single C++ program illustrating 19 Nov 2025
the public derivation, private derivation
and protected derivation. Write a C++ that
illustrates the concept of virtual base
class.
55 Write a C++ program illustrating virtual 19 Nov 2025
function.
56 Write a C++ program illustrating Function 19 Nov 2025
overloading.
57 Write a C++ program illustrating operator 19 Nov 2025
overloading.
58 Write a program illustrating Constructor 19 Nov 2025
overloading.
59 Write a C++ program to demonstrate the 19 Nov 2025
use of try-catch blocks to handle a division
by zero exception. Prompt the user to
enter two integers and perform division,
catching and handling any exceptions that
may occur
60 Develop a C++ program that uses 19 Nov 2025
exception handling to handle an out-of
range exception when accessing elements
of an array. Prompt the user to enter the
index of an array and catch any out-of
range exceptions.
61 Create a C++ program that demonstrates 19 Nov 2025
the concept of rethrowing exceptions.
Write a function that throws an exception,
then catches it and rethrows it. Finally,
catch the rethrown exception in the main
function and display an appropriate
message.
62 Write a C++ program that prompts the 19 Nov 2025
user to enter their name and age, then
displays the information in a formatted
manner using setw and left manipulators.
63 Write a C++ program that reads a floating 19 Nov 2025
point number from the user and displays it
with precision up to 3 decimal places
using the setprecision manipulator
PROGRAM 1: Write a program for Adding two numbers in C++.

Code:

#include <iostream>

using namespace std;

int main(){

int num1, num2;

cout<<"Enter the numbers:";

cin>>num1>>num2;

int sum=num1+num2;

cout<<"The sum is:"<<sum<<endl;

Output:
PROGRAM 2: Write a C++ program to check if a number is even or odd.

Code:

#include <iostream>

using namespace std;

int main(){

int num;

cout<<"Enter the number:";

cin>>num;

if (num&1){

cout<<"Number is odd"<<endl;

}else{

cout<<"Number is even"<<endl;

Output:
PROGRAM 3: Write a program to swap two numbers in C++.

Code:

#include <iostream>

using namespace std;

int main(){

int a=45;

int b=64;

cout<<"Before:"<<endl;

cout<<"a:"<<a<<endl;

cout<<"b:"<<b<<endl;

cout<<endl;

int temp=a;

a=b;

b=temp;

cout<<"After:"<<endl;

cout<<"a:"<<a<<endl;

cout<<"b:"<<b<<endl;

Output:

PROGRAM 4: Write a C++ program to find the largest number among three numbers.
Code:
#include <iostream>

using namespace std;

int main(){

int num1,num2,num3;

cout<<"Enter the numbers:";

cin>>num1>>num2>>num3;

if (num1>num2 && num1>num3){

cout<<num1<<" is the largest"<<endl;

}else if (num2>num1 && num2 >num3){

cout<<num2<<" is the largest"<<endl;

}else{

cout<<num3<<" is the largest"<<endl;

Output:

PROGRAM 5: Write a C++ Program to Find the sum of all the natural numbers from 1 to n.
Code:
#include <iostream>

using namespace std;

int main(){

int n;

cout<<"Enter the value of n:";

cin>>n;

int sum=0;

for (int i=1;i<=n;i++){

sum+=i;

cout<<"The sum is:"<<sum<<endl;

Output:

PROGRAM 6: Write a program in C++ to check whether a number is prime or not.

Code:
#include <iostream>

using namespace std;

int main(){

int n;

cout<<"Enter the value:";

cin>>n;

bool prime=true;

for (int i=2;i<n;i++){

if (n%i==0){

prime=false;

if (prime){

cout<<"It is prime"<<endl;

}else{

cout<<"It is not prime."<<endl;

Output:

PROGRAM 7: Write a C++ program to compute the power a given number to a given power.

Code:
#include <iostream>
using namespace std;

int main(){

int num,power;

cout<<"Enter the values:";

cin>>num>>power;

int ans=num;

if(power==0){

cout<<1<<endl;

}else if(power==1){

cout<<ans<<endl;

}else{

for (int i=1; i<power;i++){

ans*=num;

cout<<ans;

Output:

PROGRAM 8: Write a program for adding two numbers in C++ using classes and objects.

Code:
#include <iostream>
using namespace std;

class Add{

public:

int num1, num2;

void addNums(int num1,int num2){

cout<<"The sum is:"<<num1+num2<<endl;

};

int main(){

Add add1;

add1.num1=5;

add1.num2=12;

[Link](add1.num1,add1.num2);

Output:

PROGRAM 9: Write a program to check whether a number is odd or


even in C++ using classes and objects.
Code:
#include <iostream>

using namespace std;

class OddOrEven{

public:

int num;

void check(int num){

if (num&1){

cout<<"Number is odd"<<endl;

}else{

cout<<"Number is even"<<endl;

};

int main(){

OddOrEven program;

[Link]=10;

[Link]([Link]);

Output:

PROGRAM 10: Write a program to swap two numbers in C++ using classes and
objects.
Code:
#include <iostream>

using namespace std;

class Swap{

public:

int num1,num2;

void swapped(int num1,int num2){

cout<<"Before:"<<endl;

cout<<"Num1:"<<num1<<" "<<"Num2:"<<num2<<endl;

int temp=num1;

num1=num2;

num2=temp;

cout<<"After:"<<endl;

cout<<"Num1:"<<num1<<" "<<"Num2:"<<num2<<endl;

};

int main(){

Swap check;

check.num1=15;

check.num2=30;

[Link](check.num1,check.num2);

Output:

PROGRAM 11: Write a program to find the largest number among three numbers
in C++ using classes and objects.
Code:
#include <iostream>

using namespace std;

class Largest{

public:

int num1,num2,num3;

void find(int num1,int num2,int num3){

if (num1>num2 && num1>num3){

cout<<num1<<" is the largest"<<endl;

}else if(num2>num1 && num2>num3){

cout<<num2<<" is the largest"<<endl;

}else{

cout<<num3<<" is the largest"<<endl;

};

int main(){

Largest check;

check.num1=12;

check.num2=34;

check.num3=1;

[Link](check.num1,check.num2,check.num3);

Output:

PROGRAM 12: Write a program to find the sum of all the natural
numbers from 1 to n in C++ using classes and objects.
Code:
#include <iostream>

using namespace std;

class Sum{

public:

int num;

int sum=0;

void find(int num){

for (int i=1;i<=num;i++){

sum+=i;

cout<<"The sum is:"<<sum<<endl;

};

int main(){

Sum check;

[Link]=5;

[Link]([Link]);

Output:

PROGRAM 13: Write a program to check whether a number is prime or not in C++
using classes and objects.
Code:
#include <iostream>

using namespace std;

class Prime{

public:

int num;

void find(int num){

bool result=true;

for (int i=2; i<num;i++){

if (num%i==0){

result=false;

if (result){

cout<<"Num is prime"<<endl;

}else{

cout<<"Num is not prime"<<endl;

};

int main(){

Prime check;

[Link]=45;

[Link]([Link]);

Output:
PROGRAM 14: Write a program to compute the power a given number
to a given power in C++ using classes and objects.
Code:
#include <iostream>

using namespace std;

class Power{

public:

int num, power;

void find(int num, int power){

int ans=1;

for (int i=1;i<=power;i++){

ans*=num;

cout<<"The result is:"<<ans<<endl;

};

int main(){

Power check;

[Link]=2;

[Link]=3;

[Link]([Link], [Link]);

Output:
PROGRAM 15: Write a C++ program using class and object to check
whether a given year is a leap year or not.
Code:
#include <iostream>

using namespace std;

class Leap{

public:

int year;

void find(int year){

bool leap=false;

if (year%400==0 || (year%4==0 && year%100==0)){

leap=true;

if (leap){

cout<<"It is a leap year"<<endl;

}else{

cout<<"It is not a leap year"<<endl;

};

int main(){

Leap check;

[Link]=2015;

[Link]([Link]);

Output:
PROGRAM 16: Write a C++ program using class and object to accept a
coordinate point (x, y) in the XY coordinate system and determine in
which quadrant the point lies.
Code:
#include <iostream>

using namespace std;

class Coordinate{

public:

int x,y;

void find(int x,int y){

if (x>0 && y>0){

cout<<"Lies in the first quadrant"<<endl;

}else if(x<0 && y>0){

cout<<"Lies in the second quadrant"<<endl;

}else if(x<0 && y<0){

cout<<"Lies in the third quadrant"<<endl;

}else if(x>0 && y<0){

cout<<"Lies in the fourth quadrant"<<endl;

}else if(x!=0 && y==0){

cout<<"Lies on the x-axis"<<endl;

}else if(x==0 && y!=0){

cout<<"Lies on the y-axis"<<endl;


}else{

cout<<"Lies on the origin"<<endl;

};

int main(){

Coordinate check;

check.x=0;

check.y=0;

[Link](check.x,check.y);

Output:
PROGRAM 17: Write a C++ program using class and object to read a
student’s Roll Number, Name, and marks in three subjects. Calculate the
total marks, percentage, division, and grade of the student, and display
the result.
Code:
#include <iostream>

using namespace std;

class Student{

public:

int id;

string name;

int marks1,marks2,marks3;

void display(int marks1, int marks2,int marks3){

cout<<"ID is:"<<id<<endl;

cout<<"Name is:"<<name<<endl;

int sum=marks1+marks2+marks3;

float percentage= (sum/300.0)*100;

cout<<"Sum is:"<<sum<<endl;

cout<<"Percentage is:"<<percentage<<endl;
if (percentage>=60){

cout<<"Grade A"<<endl;

}else if(percentage>=45){

cout<<"Grade B"<<endl;

}else if(percentage>=33){

cout<<"Grade C"<<endl;

}else{

cout<<"Fail"<<endl;

};

int main(){

Student student1;

[Link]=101;

[Link]="OOPS";

student1.marks1=78;

student1.marks2=87;

student1.marks3=92;

[Link](student1.marks1,student1.marks2, student1.marks3);

Output:
PROGRAM 18: Write a C++ program using class and object to display the first N
terms of odd natural numbers and their sum.
Code:
#include <iostream>

using namespace std;

class OddNatural{

public:

int num;

void display(int num){

int sum=0;

for (int i=1,count =0; count<num;i+=2,count++){

cout<<i<<" ";

sum+=i;

cout<<endl;

cout<<"Sum is:"<<sum<<endl;

};

int main(){

OddNatural check;

[Link]=5;
[Link]([Link]);

Output:

PROGRAM 19: Write a C++ program using class and object to check
whether a given number is a palindrome or not.
Code:
#include <iostream>

using namespace std;

class Palindrome{

public:

int num;

void check(int num){

int n=num;

int rev=0;

while(n>0){

int digit=n%10;

rev=rev*10+digit;

n=n/10;

if(rev==num){

cout<<"It is a palindrome"<<endl;

}else{

cout<<"It is not a palindrome"<<endl;


}

};

int main(){

Palindrome p1;

[Link]=12321;

[Link]([Link]);

Output:
PROGRAM 20: Basic Array Input and Output Using Class. Create a class
ArrayHandler that stores an array of integers. Include methods to Input n elements
into the array and Display the array elements.
Code:
#include <iostream>

using namespace std;

class ArrayHandler{

public:

int size;

void insertArray(int *arr, int size){

cout<<"Enter the elements:";

for (int i=0; i<size;i++){

cin>>arr[i];

cout<<"Elements are:";

for (int i=0; i<size;i++){

cout<<arr[i]<<" ";

};

int main(){

ArrayHandler array1;

[Link]=5;

int arr[[Link]];

[Link](arr, [Link]);

Output:
PROGRAM 21: Write C++ program to Find Maximum and Minimum
Element in an Array using Class.
Code:
#include <iostream>

#include <algorithm>

using namespace std;

class ArrayMinMax{

public:

int size;

int mini=INT_MAX;

int maxi=INT_MIN;

void insertArray(int *arr, int size){

cout<<"Enter the elements:";

for (int i=0; i<size;i++){

cin>>arr[i];

cout<<"Elements are:";

for (int i=0; i<size;i++){

cout<<arr[i]<<" ";

}cout<<endl;

void array(int *arr, int size){

for (int i=0; i<size;i++){

mini=min(arr[i],mini);

cout<<"The minimum element is:"<<mini<<endl;


for (int i=0; i<size;i++){

maxi=max(arr[i],maxi);

cout<<"The maximum elements is:"<<maxi<<endl;

};

int main(){

ArrayMinMax array1;

[Link]=5;

int arr[[Link]];

[Link](arr,[Link]);

[Link](arr,[Link]);

Output:
PROGRAM 22: Write C++ program using class to Sort the Array in
Ascending Order.
Code:
#include <iostream>

#include <algorithm>

using namespace std;

class SortArray{

public:

int size;

void insertArray(int *arr, int size){

cout<<"Enter the elements:";

for (int i=0; i<size;i++){

cin>>arr[i];

cout<<"Elements are:";

for (int i=0; i<size;i++){

cout<<arr[i]<<" ";

}cout<<endl;

void sort(int *arr, int size){

for (int i=0; i<size;i++){

for (int j=i+1; j<size;j++){

if (arr[i]>arr[j]){

swap(arr[i],arr[j]);

}
cout<<"The sorted array is:";

for (int i=0; i<size;i++){

cout<<arr[i]<<" ";

};

int main(){

SortArray array1;

[Link]=5;

int arr[[Link]];

[Link](arr, [Link]);

[Link](arr,[Link]);

Output:
PROGRAM 23: Write C++ program using class to Search for an Element in
the Array.
Code:
#include <iostream>

using namespace std;

class LinearArray{

public:

int size;

int target;

void insertArray(int *arr, int size){

cout<<"Enter the elements:";

for (int i=0; i<size;i++){

cin>>arr[i];

cout<<"Elements are:";

for (int i=0; i<size;i++){

cout<<arr[i]<<" ";

}cout<<endl;

bool linear(int *arr,int size, int target){

for (int i=0; i<size;i++){

if (arr[i]==target){

return true;

return false;

}
};

int main(){

LinearArray array1;

[Link]=5;

int arr[[Link]];

[Link](arr,[Link]);

cout<<"Enter the element you want to search for:";

cin>>[Link];

bool found=[Link](arr, [Link], [Link]);

if (found){

cout<<"Target found"<<endl;

}else{

cout<<"Target not found"<<endl;

Output:
PROGRAM 24: Write a C++ Program using class that Count Frequency of
Elements in the Array. Create a method that Counts how many times
each unique element appears in the array and Displays the frequency.
Code:
#include <iostream>

using namespace std;

class FrequencyCounter{

public:

int size;

void insertArray(int *arr, int size){

cout<<"Enter the elements:";

for (int i=0; i<size;i++){

cin>>arr[i];

cout<<"Elements are:";

for (int i=0; i<size;i++){

cout<<arr[i]<<" ";

}cout<<endl;

void countFrequency(int *arr, int size){

bool visited[size];

for (int i=0; i<size;i++){

visited[i]=false;

for (int i=0; i<size;i++){


if (visited[i]==true){

continue;

int count=1;

for (int j=i+1; j<size;j++){

if (arr[i]==arr[j]){

visited[j]=true;

count++;

cout<<arr[i]<<"->"<<count<<endl;

};

int main(){

FrequencyCounter array1;

[Link]=8;

int arr[[Link]];

[Link](arr,[Link]);

[Link](arr, [Link]);

Output:
PROGRAM 25: Write a C++ program that defines a function int
square(int num) to return the square of a given number. In the main()
function, prompt the user to enter an integer and display its square
using the function.
Code:
#include <iostream>

using namespace std;

class Square{

public:

int num;

void square(int num){

int sq=num*num;

cout<<"The square of the given number:"<<sq<<endl;

};

int main(){

Square s1;

cout<<"Enter the number whose square you want:";

cin>>[Link];

[Link]([Link]);

Output:
PROGRAM 26: Write a C++ program using an inline function float
area(float radius) to calculate and return the area of a circle. In the
main() function, take input for the radius and display the result.
Code:
#include <iostream>

using namespace std;

inline float area(float radius){return 3.14*radius*radius;}

int main(){

float radius;

cout<<"Enter the radius:";

cin>>radius;

cout<<"The area for the given radius:"<<area(radius)<<endl;

Output:
PROGRAM 27: Write a C++ program to define a function float
calculateInterest(float principal, float rate = 5.0, int time = 2) that
calculates and returns simple interest using the formula SI = (P * R * T) /
100. Call the function with different combinations of arguments (all,
two, one) to demonstrate default argument behavior.
Code:
#include <iostream>

using namespace std;

float calculateInterest(float principal, float rate = 5.0, int time = 2){

int si=(principal*rate*time)/100;

return si;

int main(){

int si1=calculateInterest(1000,6,3);

int si2=calculateInterest(1000,6);

int si3=calculateInterest(1000);

cout<<"Using all three arguments:"<<si1<<endl;

cout<<"Using two arguments:"<<si2<<endl;

cout<<"Using one argument"<<si3<<endl;

Output:
PROGRAM 28: Write a C++ program to compare the behavior of function
overloading and default arguments by defining:
 One function int add(int a, int b)
 Another function int add(int a, int b = 0, int c = 0)
Call the function with different sets of arguments and explain what happens.
Code:
#include <iostream>

using namespace std;

int add(int num1, int num2){

cout<<"Function with two arguments is called."<<endl;

return num1+num2;

int add(int num1, int num2=0 , int num3=0){

cout<<"Function with three arguments is called."<<endl;

return num1+num2+num3;

int main(){

int test1=add(5,10);

cout<<test1<<endl;

cout<<endl;

int test2=add(5,10,15);

cout<<test2<<endl;

Output:

The error occurs because C++ does not allow function overloading where the only difference is
default arguments.
PROGRAM 29: Create a C++ program that uses an inline function int
max(int a, int b) to return the maximum of two numbers. In the main()
function, ask the user for two integers and print the maximum using the
function.
Code:
#include <iostream>

using namespace std;

inline int maxi(int num1,int num2){return max(num1,num2);}

int main(){

int num1,num2;

cout<<"Enter the two numbers:";

cin>>num1>>num2;

int ans=maxi(num1,num2);

cout<<"The maximum amongst the two is:"<<ans<<endl;

Output:
PROGRAM 30: Write a C++ program that defines a function void printDetails(string
name, int age = 18, string city = "Unknown"). In the main() function, call
printDetails():
 with all arguments
 with one or two arguments
Demonstrate how default values are used for the missing parameters.
Code:
#include <iostream>

using namespace std;

void printDetails(string name, int age = 18, string city = "Unknown"){

cout<<"Name:"<<name<<endl;

cout<<"Age:"<<age<<endl;

cout<<"City:"<<city<<endl;

int main(){

printDetails("Mila",20,"CA");

cout<<endl;

printDetails("Alicia",19);

cout<<endl;

printDetails("John");

Output:
PROGRAM 31: Create a class BitwiseDemo with two integers and methods to
perform AND, OR, and XOR.
Code:

#include <iostream>

using namespace std;

class BitwiseDemo{

public:

int num1;

int num2;

void andNum(int num1,int num2){

cout<<"AND of the two numbers:"<<(num1&num2)<<endl;

void orNum(int num1,int num2){

cout<<"OR of the two numbers:"<<(num1|num2)<<endl;

void xorNum(int num1,int num2){

cout<<"XOR of the two numbers:"<<(num1^num2)<<endl;

};

int main(){

BitwiseDemo demo1;

demo1.num1=9;

demo1.num2=3;

[Link](demo1.num1,demo1.num2);

[Link](demo1.num1,demo1.num2);

[Link](demo1.num1,demo1.num2);

Output:
PROGRAM 32: Create a class NumberCheck with a method isEven(int n) that
uses the bitwise AND operator (n & 1) to check if a number is even.
Code:
#include <iostream>

using namespace std;

class NumberCheck{

public:

int num;

void isEven(int num){

if (num&1){

cout<<"The given number is odd"<<endl;

}else{

cout<<"The number is even"<<endl;

};

int main(){

NumberCheck demo1;

[Link]=4;

[Link]([Link]);

Output:
PROGRAM 33: Create a class Swapper with a method swap(int a, int b) that
swaps two numbers using the XOR (^) operator, and display the values before
and after swapping.
Code:
#include <iostream>

using namespace std;

class Swapper{

public:

int num1;

int num2;

void Swap(int num1, int num2){

cout<<"The values before swapping:"<<endl;

cout<<"num1:"<<num1<<endl;

cout<<"num2:"<<num2<<endl;

num1=num1^num2;

num2=num1^num2;

num1=num1^num2;

cout<<"The values after swapping:"<<endl;

cout<<"num1:"<<num1<<endl;

cout<<"num2:"<<num2<<endl;

};

int main(){

Swapper demo1;

demo1.num1=7;

demo1.num2=4;
[Link](demo1.num1,demo1.num2);

Output:

PROGRAM 34: Create a class BitCounter with a method countOnes(int n) that


uses bitwise operators to count the number of 1s in the binary representation of
a number.
Code:
#include <iostream>

using namespace std;

class BitCounter{

public:

int num;

int countOnes(int num){

int count=0;

while (num>0){

if (num&1){

count++;

num=num>>1;

return count;
}

};

int main(){

BitCounter demo1;

[Link]=7;

int result=[Link]([Link]);

cout<<"Count of setbits:"<<result<<endl;

Output:

PROGRAM 35: Create a class ShiftDemo with methods multiplyBy2(int n) and


divideBy2(int n) using left shift (<<) and right shift (>>).
Code:
#include <iostream>

using namespace std;

class ShiftDemo{

public:

int num;

int multiplyBy2(int num){

return num<<1;

int divideBy2(int num){

return num>>1;

}
};

int main(){

ShiftDemo demo1;

[Link]=9;

int prod=demo1.multiplyBy2([Link]);

int div=demo1.divideBy2([Link]);

cout<<"Multiply by 2:"<<prod<<endl;

cout<<"Divide by 2:"<<div<<endl;

Output:

PROGRAM 36: Write a program to declare an integer, store its address in a


pointer, and display both the value and address.
Code:
#include <iostream>

using namespace std;

class Pointer{

public:

int num;

int *ptr;

void display(int num){

ptr=&num;

cout<<"Value:"<<num<<endl;
cout<<"Address:"<<ptr<<endl;

};

int main(){

Pointer demo1;

[Link]=9;

[Link]([Link]);

Output:

PROGRAM 37: Write a program to access elements of an array using pointers


instead of the array index.
Code:
#include <iostream>

using namespace std;

class Access{

public:

int arr[5];

int size;

void display(int *arr, int size){


for (int i=0; i<size;i++){

cout<<arr[i]<<" ";

};

int main(){

Access demo1;

[Link][0]=1;

[Link][1]=2;

[Link][2]=3;

[Link][3]=4;

[Link][4]=5;

[Link]=5;

[Link]([Link],[Link]);

Output:

PROGRAM 38: Write a function swap(int *a, int *b) that swaps two numbers
using pointers.
Code:
#include <iostream>

using namespace std;

class Swap{

public:
int num1;

int num2;

void swap(int *num1, int *num2){

cout<<"Before swapping:"<<endl;

cout<<"num1:"<<*num1<<endl;

cout<<"num2:"<<*num2<<endl;

cout<<endl;

int temp=*num1;

*num1=*num2;

*num2=temp;

cout<<"After swapping:"<<endl;

cout<<"num1:"<<*num1<<endl;

cout<<"num2:"<<*num2<<endl;

};

int main(){

Swap demo1;

demo1.num1=5;

demo1.num2=8;

[Link](&demo1.num1,&demo1.num2);

Output:
PROGRAM 39: Write a program to calculate the sum of elements of an array
using pointers.
Code:
#include <iostream>

using namespace std;

class Add{

public:

int display(int *arr, int size){

int *p=arr;

int total=0;

for (int i=0; i<size; i++){

total+=(*p+i);

return total;

};

int main(){
Add demo1;

int arr[5]={1,2,3,4,5};

int result=[Link](arr,5);

cout<<"The sum is:"<<result<<endl;

Output:

PROGRAM 40: Write a function that takes a pointer to an integer and increments
its value by 1.
Code:
#include <iostream>

using namespace std;

class Pointer{

public:

int num;

void display(int num){

int *p=&num;

cout<<"Before increment:";

cout<<*p<<endl;

cout<<endl;

cout<<"After increment:";

(*p)++;

cout<<(*p)<<endl;

}
};

int main(){

Pointer p1;

[Link]=5;

[Link]([Link]);

Output:

PROGRAM 41:
Create a class BankAccount with private members accountNumber and balance.
Write public functions to set and display values.
Try accessing balance directly in main() (should give error – comment it out).
(Concept: Data Hiding)

Code:
#include <iostream>
using namespace std;

class BankAccount {
private:
int accountNumber;
double balance;

public:
void setValues(int accNum, double bal) {
accountNumber = accNum;
balance = bal;
}

void displayValues() {
cout << "Account Number: " << accountNumber << endl;
cout << "Balance: ₹" << balance << endl;
}
};

int main() {
BankAccount b1;
[Link](12345, 5000.75);
[Link]();
return 0;
}
Output-

PROGRAM 42:
Create a class Student with private members name and marks.
Use a friend function to display student details.
(Concept: Friend Function)

Code:

#include <iostream>

using namespace std;

class Student {

private:

string name;

int marks;

public:

Student(string n, int m) {

name = n;

marks = m;

friend void displayDetails(Student s);

};

void displayDetails(Student s) {

cout << "Name: " << [Link] << endl;

cout << "Marks: " << [Link] << endl;

int main() {

Student s1("Ishh", 95);

displayDetails(s1);

return 0;

}
Output:

PROGRAM 43:

Create a class Counter with a static variable count.


Use a member function to increment and display the count.
Call it with multiple objects.
(Concept: Static Variable)

Code:

#include <iostream>

using namespace std;

class Counter {

private:

static int count;

public:

void increment() {

count++;

void displayCount() {

cout << "Current Count: " << count << endl;

}
};

int Counter::count = 0;

int main() {

Counter c1, c2, c3;

[Link]();

[Link]();

[Link]();

[Link]();

[Link]();

[Link]();

return 0;

Output:

PROGRAM 44:

Create a class MyClass with a private static variable data.


Use a friend function to modify and display data.
Call the friend function multiple times.
(Concept: Static + Friend Function)

Code:
#include <iostream>

using namespace std;

class MyClass {

private:

static int data;

public:

friend void modifyData(int value);

};

int MyClass::data = 0;

void modifyData(int value) {

MyClass::data += value;

cout << "Data after modification: " << MyClass::data << endl;

int main() {

modifyData(10);

modifyData(5);

modifyData(-3);

return 0;

Output:
PROGRAM 45:

Create class Employee with private members empID, salary, and a static empCount.
Use a setter function to assign values and increment empCount.
Use a static function to return total employees.
(Concept: Data Hiding + Static Variable)

Code:

#include <iostream>

using namespace std;

class Employee {

private:

int empID;

double salary;

static int empCount;

public:

void setDetails(int id, double sal) {

empID = id;

salary = sal;

empCount++;

void displayDetails() {

cout << "Employee ID: " << empID << ", Salary: ₹" << salary << endl;

static int totalEmployees() {

return empCount;

};
int Employee::empCount = 0;

int main() {

Employee e1, e2;

[Link](101, 45000);

[Link](102, 55000);

[Link]();

[Link]();

cout << "Total Employees: " << Employee::totalEmployees() << endl;

return 0;

Output:

PROGRAM 46:

Create a base class Person with data members name and age, and a derived class Student that
adds a studentID and a method to display all details.
(Concept: Single Inheritance)

Code:

#include <iostream>

using namespace std;

class Person {

protected:
string name;

int age;

public:

void setPersonDetails(string n, int a) {

name = n;

age = a;

};

class Student : public Person {

private:

int studentID;

public:

void setStudentID(int id) {

studentID = id;

void displayDetails() {

cout << "Name: " << name << endl;

cout << "Age: " << age << endl;

cout << "Student ID: " << studentID << endl;

};

int main() {

Student s1;

[Link]("Ishh", 20);

[Link](1001);

[Link]();
return 0;

Output:

PROGRAM 47:

Define a base class Employee with protected members empID and salary.
Create a derived class Manager that adds bonus and a function calculateTotalSalary() to compute
total pay.
(Concept: Inheritance + Protected Members)

Code:

#include <iostream>

using namespace std;

class Employee {

protected:

int empID;

double salary;

public:

void setEmployeeDetails(int id, double sal) {

empID = id;

salary = sal;

};

class Manager : public Employee {

private:
double bonus;

public:

void setBonus(double b) {

bonus = b;

double calculateTotalSalary() {

return salary + bonus;

void displayDetails() {

cout << "Employee ID: " << empID << endl;

cout << "Basic Salary: ₹" << salary << endl;

cout << "Bonus: ₹" << bonus << endl;

cout << "Total Salary: ₹" << calculateTotalSalary() << endl;

};

int main() {

Manager m1;

[Link](201, 50000);

[Link](10000);

[Link]();

return 0;

Output:
PROGRAM 48:

Define a base class Account that stores accountNumber and balance (private).
Provide public functions to set and get these values. Derive a class SavingsAccount that adds
interestRate and a function to calculate interest.
(Concept: Inheritance + Data Hiding)

Code:

#include <iostream>

using namespace std;

class Account {

private:

int accountNumber;

double balance;

public:

void setAccountDetails(int accNo, double bal) {

accountNumber = accNo;

balance = bal;

int getAccountNumber() {

return accountNumber;

double getBalance() {

return balance;

}
};

class SavingsAccount : public Account {

private:

double interestRate;

public:

void setInterestRate(double rate) {

interestRate = rate;

double calculateInterest() {

return (getBalance() * interestRate) / 100;

void displayAccountDetails() {

cout << "Account Number: " << getAccountNumber() << endl;

cout << "Balance: ₹" << getBalance() << endl;

cout << "Interest Rate: " << interestRate << "%" << endl;

cout << "Calculated Interest: ₹" << calculateInterest() << endl;

};

int main() {

SavingsAccount s1;

[Link](55501, 10000);

[Link](5.5);

[Link]();

return 0;

}
Output:

PROGRAM 49: Class for a geometric shape with constructor and destructor

Code:

#include <iostream>

using namespace std;

class Rectangle {

int width, height;

public:

Rectangle(int w, int h) : width(w), height(h) {

cout << "Rectangle created (w=" << width << ", h=" << height << ")\n";

int area() const { return width * height; }

~Rectangle() {

cout << "Rectangle destroyed (w=" << width << ", h=" << height << ")\n";

};

int main() {

Rectangle r(5, 3);

cout << "Area: " << [Link]() << endl;

// destructor message will appear when r goes out of scope

return 0;

}
Output:

PROGRAM 50: Simple bank account class with constructor and destructor

Code:

#include <iostream>

#include <string>

using namespace std;

class BankAccount {

string owner;

int accountNumber;

double balance;

public:

BankAccount(const string& name, int accNo, double bal)

: owner(name), accountNumber(accNo), balance(bal) {

cout << "Account opened for " << owner << " (Acc#: " << accountNumber << ")\n";

void deposit(double amt) { balance += amt; }

bool withdraw(double amt) {

if (amt > balance) return false;

balance -= amt;

return true;

void display() const {

cout << "Owner: " << owner << ", Acc#: " << accountNumber
<< ", Balance: " << balance << endl;

~BankAccount() {

cout << "Account object for " << owner << " is being destroyed.\n";

};

int main() {

BankAccount a("Ishh", 123456, 5000.0);

[Link]();

[Link](1500.0);

cout << "After deposit: ";

[Link]();

// destructor prints on scope exit

return 0;

Output:

PROGRAM 51: University course class with constructor and destructor releasing dynamic memory

Code:

#include <iostream>

#include <string>

using namespace std;

class Course {
string courseName;

string* students; // dynamic array of student names

int studentCount;

public:

Course(const string& name, int n) : courseName(name), studentCount(n) {

students = new string[studentCount];

cout << "Course '" << courseName << "' created for " << studentCount << " students.\n";

for (int i = 0; i < studentCount; ++i) {

students[i] = "Student_" + to_string(i+1);

void showStudents() const {

cout << "Course: " << courseName << "\nEnrolled students:\n";

for (int i = 0; i < studentCount; ++i)

cout << " " << students[i] << '\n';

~Course() {

delete[] students;

cout << "Course '" << courseName << "' destroyed and student list memory freed.\n";

};

int main() {

Course c("Data Structures", 3);

[Link]();

return 0;

Output:
PROGRAM 52: Book class with constructor parameters and destructor releasing dynamic memory

Code:

#include <iostream>

#include <string>

using namespace std;

class Book {

string title;

string author;

int year;

string* synopsis; // dynamically allocated story/details

public:

Book(const string& t, const string& a, int y, const string& syn)

: title(t), author(a), year(y) {

synopsis = new string(syn);

cout << "Book '" << title << "' created.\n";

void display() const {

cout << "Title: " << title << "\nAuthor: " << author

<< "\nYear: " << year << "\nSynopsis: " << *synopsis << endl;

~Book() {

delete synopsis;

cout << "Book '" << title << "' destroyed and synopsis memory freed.\n";
}

};

int main() {

Book b("The Tales", "A. Writer", 2020, "A short adventure story.");

[Link]();

return 0;

Output:

PROGRAM 53: Base class Person and derived class Student (adds studentID and display)

Code:

#include <iostream>

#include <string>

using namespace std;

class Person {

public:

string name;

int age;

Person(const string& n = "", int a = 0) : name(n), age(a) {}

};
class Student : public Person {

string studentID;

public:

Student(const string& n, int a, const string& id) : Person(n, a), studentID(id) {}

void display() const {

cout << "Name: " << name << "\nAge: " << age << "\nStudent ID: " << studentID << endl;

};

int main() {

Student s("Asha", 20, "S2025001");

[Link]();

return 0;

Output:

PROGRAM 54: Base class Employee (protected empID, salary) and derived Manager with bonus
and calculateTotalSalary()

Code:

#include <iostream>

#include <string>

using namespace std;

class Employee {

protected:

int empID;
double salary;

public:

Employee(int id = 0, double sal = 0.0) : empID(id), salary(sal) {}

};

class Manager : public Employee {

double bonus;

public:

Manager(int id, double sal, double bon) : Employee(id, sal), bonus(bon) {}

double calculateTotalSalary() const {

return salary + bonus;

void show() const {

cout << "Manager ID: " << empID << ", Base Salary: " << salary

<< ", Bonus: " << bonus << ", Total: " << calculateTotalSalary() << endl;

};

int main() {

Manager m(101, 75000.0, 12000.0);

[Link]();

return 0;

Output:

PROGRAM 55: Base class Account (private accountNumber, balance) with setters/getters;
SavingsAccount derived adds interestRate and calculateInterest()

Code:
#include <iostream>

using namespace std;

class Account {

private:

long accountNumber;

double balance;

public:

void setAccountNumber(long acc) { accountNumber = acc; }

long getAccountNumber() const { return accountNumber; }

void setBalance(double b) { balance = b; }

double getBalance() const { return balance; }

};

class SavingsAccount : public Account {

double interestRate; // as percentage, e.g., 5 for 5%

public:

SavingsAccount(double rate = 0.0) : interestRate(rate) {}

double calculateInterest() const {

return (getBalance() * interestRate) / 100.0;

void show() const {

cout << "Acc#: " << getAccountNumber() << ", Balance: " << getBalance()

<< ", Interest Rate: " << interestRate << "%, Interest: " << calculateInterest() << endl;

};

int main() {

SavingsAccount s(4.5);

[Link](987654321);
[Link](10000.0);

[Link]();

return 0;

Output:

PROGRAM 56: Single program illustrating single, multiple and multilevel inheritance

Code:

#include <iostream>

using namespace std;

// Single inheritance

class A {

public:

void funA() const { cout << "A::funA()\n"; }

};

class SingleDerived : public A {

public:

void funSingle() const { cout << "SingleDerived::funSingle()\n"; }

};

// Multiple inheritance

class B {

public:

void funB() const { cout << "B::funB()\n"; }

};
class C {

public:

void funC() const { cout << "C::funC()\n"; }

};

class MultipleDerived : public B, public C {

public:

void funMulti() const { cout << "MultipleDerived::funMulti()\n"; }

};

// Multilevel inheritance (A -> Level1 -> Level2)

class Level1 : public A {

public:

void funLevel1() const { cout << "Level1::funLevel1()\n"; }

};

class Level2 : public Level1 {

public:

void funLevel2() const { cout << "Level2::funLevel2()\n"; }

};

int main() {

cout << "--- Single Inheritance ---\n";

SingleDerived s;

[Link]();

[Link]();

cout << "\n--- Multiple Inheritance ---\n";

MultipleDerived m;

[Link]();

[Link]();

[Link]();
cout << "\n--- Multilevel Inheritance ---\n";

Level2 L;

[Link](); // from A

L.funLevel1(); // from Level1

L.funLevel2(); // from Level2

return 0;

Output:

PROGRAM 57: Illustration of public, private, protected derivation and virtual base class (diamond
problem demo)

Code:

#include <iostream>

using namespace std;

class Base {

protected:

int x;

public:

Base(int v = 0) : x(v) {}

void setX(int v) { x = v; }
int getX() const { return x; }

void show() const { cout << "Base x = " << x << endl; }

};

// public / private / protected derivation demo

class PubDerived : public Base {

public:

PubDerived(int v=0) : Base(v) {}

void showPub() { cout << "PubDerived accessing x: " << x << endl; }

};

class PrivDerived : private Base {

public:

PrivDerived(int v=0) : Base(v) {}

// Base's public members become private in PrivDerived.

void setAndShow(int v) { setX(v); cout << "PrivDerived set x=" << getX() << endl; }

};

class ProtDerived : protected Base {

public:

ProtDerived(int v=0) : Base(v) {}

void showProt() { cout << "ProtDerived accessing x: " << x << endl; }

};

// Virtual base class (diamond)

class VBase {

protected:

int val;

public:

VBase(int v=0) : val(v) {}

void setVal(int v) { val = v; }


int getVal() const { return val; }

};

class Left : virtual public VBase {

public:

Left(int v=0) : VBase(v) {}

};

class Right : virtual public VBase {

public:

Right(int v=0) : VBase(v) {}

};

class Diamond : public Left, public Right {

public:

Diamond(int v=0) : VBase(v), Left(v), Right(v) {}

void showDiamond() {

// single shared VBase subobject

cout << "Diamond sees VBase::val = " << getVal() << endl;

};

int main() {

cout << "--- Public / Private / Protected Derivation ---\n";

PubDerived p(10);

[Link]();

// [Link](20); // allowed? setX is public in Base and remains public in PubDerived

[Link](20);

[Link]();

PrivDerived pr;
[Link](30); // allowed via wrapper

ProtDerived pt(40);

[Link]();

cout << "\n--- Virtual Base (Diamond) Demo ---\n";

Diamond d(99);

[Link]();

[Link](123); // sets the single VBase member

[Link]();

return 0;

Output:

PROGRAM 58: Illustrating virtual function

Code:

#include <iostream>

using namespace std;

class Shape {

public:
virtual void draw() const { cout << "Drawing a generic shape\n"; }

virtual ~Shape() = default;

};

class Circle : public Shape {

public:

void draw() const override { cout << "Drawing a circle\n"; }

};

class Rectangle : public Shape {

public:

void draw() const override { cout << "Drawing a rectangle\n"; }

};

int main() {

Shape* s1 = new Circle();

Shape* s2 = new Rectangle();

// Virtual dispatch: calls derived functions

s1->draw();

s2->draw();

delete s1;

delete s2;

return 0;

Output:
PROGRAM 59: Illustrating function overloading

Code:

#include <iostream>

using namespace std;

int add(int a, int b) {

return a + b;

double add(double a, double b) {

return a + b;

int add(int a, int b, int c) {

return a + b + c;

int main() {

cout << "add(2,3) = " << add(2,3) << '\n';

cout << "add(2.5,3.1) = " << add(2.5,3.1) << '\n';

cout << "add(1,2,3) = " << add(1,2,3) << '\n';

return 0;

Output:
PROGRAM 60: Illustrating operator overloading (Complex numbers, operator +)

Code:

#include <iostream>

using namespace std;

class Complex {

double re, im;

public:

Complex(double r = 0, double i = 0) : re(r), im(i) {}

// Operator overloading for addition

Complex operator+(const Complex& other) const {

return Complex(re + [Link], im + [Link]);

// Display without using fabs()

friend ostream& operator<<(ostream& os, const Complex& c) {

if ([Link] >= 0)

os << [Link] << " + " << [Link] << "i";

else

os << [Link] << " - " << (-[Link]) << "i"; // manually flipping the sign

return os;

};

int main() {
Complex a(2, 3), b(1, -4);

Complex c = a + b;

cout << "a = " << a << endl;

cout << "b = " << b << endl;

cout << "a + b = " << c << endl;

return 0;

Output:

PROGRAM 61: Illustrating constructor overloading

Code:

#include <iostream>

using namespace std;

class Point {

int x, y;

public:

Point() : x(0), y(0) { cout << "Default ctor: (0,0)\n"; }

Point(int a) : x(a), y(a) { cout << "Single-arg ctor: (" << x << "," << y << ")\n"; }

Point(int a, int b) : x(a), y(b) { cout << "Two-arg ctor: (" << x << "," << y << ")\n"; }

void show() const { cout << "Point = (" << x << "," << y << ")\n"; }

};
int main() {

Point p1;

Point p2(5);

Point p3(3,7);

[Link]();

[Link]();

[Link]();

return 0;

Output:

PROGRAM 62: Division by zero with try-catch (prompt user for two integers)

Code:

#include <iostream>

#include <stdexcept>

using namespace std;

int main() {

int a, b;

cout << "Enter numerator and denominator: ";

if (!(cin >> a >> b)) {


cout << "Invalid input.\n";

return 1;

try {

if (b == 0) throw runtime_error("Division by zero error");

cout << "Result: " << (a / b) << " (integer division)\n";

} catch (const runtime_error& e) {

cout << "Caught exception: " << [Link]() << '\n';

return 0;

Output:

PROGRAM 63: Handle out_of_range when accessing array elements (prompt index)

Code:

#include <iostream>

#include <vector>

#include <stdexcept>

using namespace std;

int main() {

vector<int> arr = {10, 20, 30, 40, 50};

cout << "Array has " << [Link]() << " elements (indices 0-" << [Link]()-1 << ")\n";

cout << "Enter index to access: ";


int idx;

if (!(cin >> idx)) { cout << "Invalid input.\n"; return 1; }

try {

// .at throws std::out_of_range when index is invalid

int value = [Link](idx);

cout << "Value at index " << idx << " is " << value << '\n';

} catch (const out_of_range& e) {

cout << "Caught out_of_range exception: " << [Link]() << '\n';

return 0;

Output:

PROGRAM 53: Demonstrating rethrowing exceptions

Code:

#include <iostream>

#include <stdexcept>

using namespace std;

void func() {

try {

throw runtime_error("Something bad happened in func");

} catch (const runtime_error& e) {


cout << "func caught: " << [Link]() << " -> rethrowing\n";

throw; // rethrow same exception

int main() {

try {

func();

} catch (const runtime_error& e) {

cout << "main caught rethrown exception: " << [Link]() << '\n';

return 0;

Output:

PROGRAM 54: Prompt name and age, display formatted using setw and left manipulators

Code:

#include <iostream>

#include <iomanip>

#include <string>

using namespace std;

int main() {

string name;

int age;
cout << "Enter your name: ";

getline(cin, name);

cout << "Enter your age: ";

if (!(cin >> age)) { cout << "Invalid age.\n"; return 1; }

cout << left << setw(12) << "Name:" << name << '\n';

cout << left << setw(12) << "Age:" << age << '\n';

return 0;

Output:

PROGRAM 55: Read a floating-point number and display with precision up to 3 decimal places

Code:

#include <iostream>

#include <iomanip>

using namespace std;

int main() {

double x;

cout << "Enter a floating-point number: ";

if (!(cin >> x)) { cout << "Invalid input.\n"; return 1; }

cout << fixed << setprecision(3);

cout << "Value with precision 3: " << x << '\n';


return 0;

Output:

You might also like