0% found this document useful (0 votes)
5 views

OOP&DSA Lab Final Questions

The document contains a series of programming exercises focused on object-oriented programming (OOP) concepts in C++. It includes tasks such as creating classes for student information, performing mathematical operations, using copy constructors, and implementing operator overloading. Additionally, it covers file I/O operations, inheritance, and virtual functions, providing a comprehensive overview of OOP principles in C++.

Uploaded by

nazatmohammed
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

OOP&DSA Lab Final Questions

The document contains a series of programming exercises focused on object-oriented programming (OOP) concepts in C++. It includes tasks such as creating classes for student information, performing mathematical operations, using copy constructors, and implementing operator overloading. Additionally, it covers file I/O operations, inheritance, and virtual functions, providing a comprehensive overview of OOP principles in C++.

Uploaded by

nazatmohammed
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 55

OOP Lab Final Questions

1. Write a program to take student information and display it using the student class and
its object.

#include<iostream>

using namespace std;

class Student {

public:

string name;

int age;

string id;

void display() {

cout << "Name: " << name << "\nAge: " << age << "\nID: "
<< id << endl;

};

int main() {

Student s;

cout << "Enter name, age, and ID: ";

cin >> s.name >> s.age >> s.id;

s.display();

return 0;

2. Write a program to take two inputs and find the maximum, minimum, sum, division,
subtraction, multiplication, and GCD of these two values using a class named
operations.

#include<iostream>
using namespace std;

class Operation {

public:

int a, b;

void calculate() {

cout << "Sum: " << a + b << "\nDifference: " << a - b <<
"\nProduct: " << a * b << "\nDivision: " << a / b << "\nGCD: " <<
gcd(a, b) << endl;

private:

int gcd(int x, int y) {

while (y != 0) {

int temp = y;

y = x % y;

x = temp;

return x;

};

int main() {

Operation op;

cout << "Enter two numbers: ";

cin >> op.a >> op.b;

op.calculate();

return 0;

}
3. Write a program to reverse a number by defining the class named reverse.

#include<iostream>

using namespace std;

class Reverse {

public:

int reverseNumber(int n) {

int rev = 0;

while (n > 0) {

rev = rev * 10 + (n % 10);

n /= 10;

return rev;

};

int main() {

Reverse r;

int num;

cout << "Enter a number to reverse: ";

cin >> num;

cout << "Reversed number: " << r.reverseNumber(num) << endl;

return 0;

4. Write a program to copy the content of one object to another using the copy
constructor function.
#include <iostream>

using namespace std;

class Example {

private:

int value;

public:

// Parameterized Constructor

Example(int val) {

value = val;

cout << "Parameterized Constructor called.\n";

// Copy Constructor

Example(const Example& obj) {

value = obj.value;

cout << "Copy Constructor called.\n";

// Method to display the value

void display() const {

cout << "Value: " << value << endl;

};

int main() {

// Create an object using the parameterized constructor


Example obj1(10);

cout << "Object 1: ";

obj1.display();

// Create another object using the copy constructor

Example obj2 = obj1; // Copy constructor is invoked here

cout << "Object 2 (copied from Object 1): ";

obj2.display();

return 0;

5. Write a program to copy one object to another using the concept of a copy
constructor.

#include <iostream>

using namespace std;

class Example {

private:

int value;

public:

// Parameterized Constructor

Example(int val) {

value = val;

cout << "Parameterized Constructor called.\n";

// Copy Constructor

Example(const Example& obj) {


value = obj.value;

cout << "Copy Constructor called.\n";

// Method to display the value

void display() const {

cout << "Value: " << value << endl;

};

int main() {

// Create an object using the parameterized constructor

Example obj1(20);

cout << "Object 1: ";

obj1.display();

// Create another object and explicitly invoke the copy constructor

Example obj2(obj1); // Copy constructor explicitly called here

cout << "Object 2 (copied from Object 1): ";

obj2.display();

return 0;

6. Write a program to find the maximum and minimum value of an array using an inline
function.

#include<iostream>

using namespace std;

inline int findMax(int a, int b) {


return (a > b) ? a : b;

inline int findMin(int a, int b) {

return (a < b) ? a : b;

int main() {

int x, y;

cout << "Enter two numbers: ";

cin >> x >> y;

cout << "Maximum: " << findMax(x, y) << "\nMinimum: " <<
findMin(x, y) << endl;

return 0;

7. Write a program to calculate the average of some integer values by defining a static
member function in a class.

#include<iostream>

using namespace std;

class Average {

public:

static double calculateAverage(int arr[], int size) {

int sum = 0;

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

sum += arr[i];

return static_cast<double>(sum) / size;


}

};

int main() {

int n;

cout << "Enter the number of elements: ";

cin >> n;

int arr[n];

cout << "Enter the elements: ";

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

cin >> arr[i];

cout << "Average: " << Average::calculateAverage(arr, n) <<


endl;

return 0;

8. Write a program to calculate the area of a triangle by declaring a friend function in a


class.

#include<iostream>

using namespace std;

class Triangle {

public:

double base, height;

Triangle(double b, double h) : base(b), height(h) {}

friend double calculateArea(Triangle t);

};
double calculateArea(Triangle t) {

return 0.5 * t.base * t.height;

int main() {

double base, height;

cout << "Enter base and height of the triangle: ";

cin >> base >> height;

Triangle t(base, height);

cout << "Area of the triangle: " << calculateArea(t) << endl;

return 0;

9. Write a program to display the month of birth by using an enumerated data type.

#include<iostream>

using namespace std;

enum Month { January = 1, February, March, April, May, June,


July, August, September, October, November, December };

int main() {

int monthNumber;

cout << "Enter your birth month (1-12): ";

cin >> monthNumber;

Month birthMonth = static_cast<Month>(monthNumber);

cout << "You were born in month number: " << birthMonth <<
endl;

return 0;

}
10. Write a program to display a pyramid of “*" using manipulators.

#include <iostream>

#include <iomanip> // For manipulators

using namespace std;

int main() {

int rows;

// Input: Number of rows for the pyramid

cout << "Enter the number of rows for the pyramid: ";

cin >> rows;

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

// Print leading spaces using setw

cout << setw(rows - i + 1);

// Print stars for the current row

for (int j = 1; j <= 2 * i - 1; ++j) {

cout << "*";

// Move to the next line

cout << endl;

return 0;

}
11. Write a program to find the square root of a number by passing an object to a
function.

#include <iostream>

#include <cmath>

using namespace std;

class Number {

private:

double value;

public:

Number(double val) : value(val) {}

friend void calculateSquareRoot(const Number& obj);

};

void calculateSquareRoot(const Number& obj) {

cout << sqrt(obj.value) << endl;

int main() {

Number num(16.0);

calculateSquareRoot(num);

return 0;

}
12. Write a program to find the square root of a number by returning an object from a
function.

#include <iostream>

#include <cmath>

using namespace std;

class Number {

private:

double value;

public:

Number(double val) : value(val) {}

Number calculateSquareRoot() const {

return Number(sqrt(value));

};

int main() {

Number num(25.0);

Number result = num.calculateSquareRoot();

cout << result.calculateSquareRoot() << endl;

return 0;

13. Write a program to overload the unary operator to increment or decrement an integer
number.

class UnaryOperator {

int value;
public:

UnaryOperator(int v) : value(v) {}

void operator++() { ++value; }

void operator--() { --value; }

int getValue() { return value; }

};

// Question 14: Binary Operator Overloading

class BinaryOperator {

int value;

public:

BinaryOperator(int v) : value(v) {}

BinaryOperator operator+(const BinaryOperator &obj) {

return BinaryOperator(value + obj.value);

int getValue() { return value; }

};

Int main() {

UnaryOperator u(5);

++u;

--u;

std::cout << "Unary operator value: " << u.getValue() << "\
n";
Return 0;

14. Write a program to overload the binary operator to sum two integer numbers.

class BinaryOperator {

int value;

public:

BinaryOperator(int v) : value(v) {}

BinaryOperator operator+(const BinaryOperator &obj) {

return BinaryOperator(value + obj.value);

int getValue() { return value; }

};

Int main() {

BinaryOperator b1(5), b2(10);

BinaryOperator b3 = b1 + b2;

std::cout << "Binary operator value: " << b3.getValue() << "\n";

15. Write a program to overload a function named calculateArea to measure the area of
a triangle, rectangle, and circle.

#include <iostream>

#include <cmath>
using namespace std;

class Shape {

public:

double calculateArea(double base, double height) { return 0.5 * base * height; } //


Triangle

double calculateArea(double length, double breadth) { return length * breadth; } //


Rectangle

double calculateArea(double radius) { return 3.14159 * radius * radius; } // Circle

};

int main() {

Shape shape;

cout << "Triangle Area: " << shape.calculateArea(5.0, 10.0) << endl;

cout << "Rectangle Area: " << shape.calculateArea(4.0, 6.0) << endl;

cout << "Circle Area: " << shape.calculateArea(7.0) << endl;

return 0;

16. Write a program to overload the comparator operator to compare two strings.

#include <iostream>

#include <string>

using namespace std;

class CompareStrings {

public:

bool operator ==(const string& str1, const string& str2) {

return str1 == str2;


}

};

int main() {

CompareStrings cs;

string str1 = "Hello", str2 = "World";

cout << (str1 == str2 ? "Equal" : "Not Equal") << endl;

return 0;

17. Write a program to inherit a daughter/son class to show the common properties of
her/his father and mother.

#include <iostream>

using namespace std;

class Father {

public:

void job() { cout << "Father's job\n"; }

};

class Mother {

public:

void job() { cout << "Mother's job\n"; }

};

class Daughter : public Father, public Mother {

public:

void displayJobs() {
Father::job();

Mother::job();

};

int main() {

Daughter daughter;

daughter.displayJobs();

return 0;

18. Write a program to store bank account information using file I/O in C++.

class BankAccount {

private:

string accountHolderName;

int accountNumber;

double balance;

public:

void input() {

cout << "Enter account holder's name: ";

getline(cin, accountHolderName);

cout << "Enter account number: ";

cin >> accountNumber;

cout << "Enter balance: ";

cin >> balance;

cin.ignore(); // To ignore the newline character after the balance input


}

void display() {

cout << "Account Holder: " << accountHolderName << endl;

cout << "Account Number: " << accountNumber << endl;

cout << "Balance: " << balance << endl;

void saveToFile() {

ofstream outFile("bank_account.txt", ios::app);

outFile << accountHolderName << endl;

outFile << accountNumber << endl;

outFile << balance << endl;

outFile.close();

void loadFromFile() {

ifstream inFile("bank_account.txt");

if (inFile) {

while (getline(inFile, accountHolderName)) {

inFile >> accountNumber;

inFile >> balance;

inFile.ignore(); // To ignore the newline character after balance

inFile.ignore(); // To move to the next record

display();

inFile.close();

} else {
cout << "File not found." << endl;

};

int main() {

BankAccount account;

// Input and store data

account.input();

account.saveToFile();

// Load and display data from file

cout << "\nReading from file:\n";

account.loadFromFile();

return 0;

19. Write a program to store the following shape in a file using manipulators:
Programming
Programmin
Programmi
Programm
Program
Progra
Progr
Prog
Pro
Pr
P

#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;

int main() {
ofstream file("shape_output.txt");

if (file.is_open()) {
string shape = "Programming";
for (int i = shape.length(); i > 0; --i) {
file << setw(shape.length()) << shape.substr(0, i) <<
endl;
}
file.close();
cout << "Shape stored in file successfully!" << endl;
} else {
cout << "Error opening file!" << endl;
}

return 0;
}

20. Write a program to calculate the area of a triangle, rectangle, and circle by declaring
a virtual function calculateArea.

#include <iostream>

#include <cmath>

using namespace std;

class Shape {

public:

virtual void calculateArea() = 0; // Pure virtual function

};

class Triangle : public Shape {

double base, height;

public:

Triangle(double b, double h) : base(b), height(h) {}

void calculateArea() override {


cout << "Area of Triangle: " << 0.5 * base * height <<
endl;

};

class Rectangle : public Shape {

double length, width;

public:

Rectangle(double l, double w) : length(l), width(w) {}

void calculateArea() override {

cout << "Area of Rectangle: " << length * width << endl;

};

class Circle : public Shape {

double radius;

public:

Circle(double r) : radius(r) {}

void calculateArea() override {

cout << "Area of Circle: " << M_PI * radius * radius <<
endl;

};

int main() {

Shape *shapes[3];
shapes[0] = new Triangle(10, 5);

shapes[1] = new Rectangle(4, 6);

shapes[2] = new Circle(3);

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

shapes[i]->calculateArea();

delete shapes[i];

return 0;

DSA Lab Final Questions


Array:
1. Suppose there are 60 students in my class. They have 4 class tests of a course. Find
out the average of the best 3 class tests for each student.
2. Take a two-dimensional array with m×nm \times n size. Write a program to find out
the summation of the boundary elements, where mm and nn are user inputs.
3. Take a two-dimensional array with m×nm \times n size. Write a program to find out
the summation of the diagonal elements, where mm and nn are user inputs.
4. Write a program to sort data in an ascending order. Write a program to rearrange the
elements of an array in descending order without using any sorting algorithm and any
extra data structure.

#include <iostream>

#include <vector>

#include <algorithm> // For sort()


using namespace std;

// Function to sort an array in ascending order

void sortAscending(vector<int>& arr) {

sort(arr.begin(), arr.end());

// Function to rearrange elements in descending order without a sorting algorithm

void rearrangeDescending(vector<int>& arr) {

int n = arr.size();

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

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

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

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

int main() {

vector<int> array = {10, 3, 5, 7, 2, 8, 1};

cout << "Original Array: ";

for (int num : array) {

cout << num << " ";

cout << endl;

// Sort in ascending order


vector<int> ascArray = array;

sortAscending(ascArray);

cout << "Array in Ascending Order: ";

for (int num : ascArray) {

cout << num << " ";

cout << endl;

// Rearrange in descending order without sorting algorithm

vector<int> descArray = array;

rearrangeDescending(descArray);

cout << "Array in Descending Order: ";

for (int num : descArray) {

cout << num << " ";

cout << endl;

return 0;

5. Take a two-dimensional array of size n×nn \times n. Write a program to remove the
column and row where zero (0) is found.

#include <iostream>

#include <vector>

#include <set>

using namespace std;


// Function to remove rows and columns containing zero

void removeRowColWithZero(vector<vector<int>>& matrix) {

int rows = matrix.size();

int cols = matrix[0].size();

set<int> rowsWithZero, colsWithZero;

// Identify rows and columns with zero

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

for (int j = 0; j < cols; ++j) {

if (matrix[i][j] == 0) {

rowsWithZero.insert(i);

colsWithZero.insert(j);

// Create a new matrix excluding rows and columns with zero

vector<vector<int>> result;

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

if (rowsWithZero.count(i)) continue; // Skip this row

vector<int> newRow;

for (int j = 0; j < cols; ++j) {

if (colsWithZero.count(j)) continue; // Skip this column

newRow.push_back(matrix[i][j]);

}
if (!newRow.empty()) {

result.push_back(newRow);

// Update the original matrix

matrix = result;

removeRowColWithZero(matrix);

cout << "\nModified 2D Array:" << endl;

for (const auto& row : matrix) {

for (int num : row) {

cout << num << " ";

cout << endl;

return 0;

Sorting and Searching:


1. Write a program to sort a group of elements using the bubble sort. Show the results
for each step.

void bubbleSort(int arr[], int n)

for (int i = 0; i < n - 1; i++)


{

bool swapped = false;

for (int j = 0; j < n - i - 1; j++)

if (arr[j] > arr[j + 1])

swap(arr[j], arr[j + 1]);

swapped = true;

if (!swapped)

break;

2. Write a program to sort a group of elements using the selection sort. Display the
results for each step.

void selectionSort(int arr[], int n)

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

int minIndex = i;

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

if(arr[j] < arr[minIndex])

minIndex = j;

swap(arr[minIndex], arr[i]);
}

3. Write a program to sort a group of elements using the insertion sort. Show the results
for each step.

void i_s(int arr[], int n)

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

int j = i;

while (j > 0 && arr[j - 1] > arr[j])

swap(arr[j - 1], arr[j]);

j--;

4. Write a program to sort a group of elements using the merge sort. Display the results
for each step.

void merge(int arr[], int left, int mid, int right) {

int i = left, j = mid + 1, k = 0;

int temp[right - left + 1];

while (i <= mid && j <= right) {

if (arr[i] <= arr[j]) temp[k++] = arr[i++];

else temp[k++] = arr[j++];

}
while (i <= mid) temp[k++] = arr[i++];

while (j <= right) temp[k++] = arr[j++];

for (i = left, k = 0; i <= right; i++, k++) arr[i] = temp[k];

void mergeSort(int arr[], int left, int right) {

if (left >= right) return;

int mid = left + (right - left) / 2;

mergeSort(arr, left, mid); // Recursively sort the left


half

mergeSort(arr, mid + 1, right); // Recursively sort the right


half

merge(arr, left, mid, right); // Merge the sorted halves

5. Write a program to sort a group of elements using the quick sort. Show the results for
each step.

int quick_partition(int arr[], int low, int high)

int pivot = arr[low], i = low - 1;

for (int j = low; j < high; j++)

if (arr[j] < pivot) // If current element is smaller


than pivot

i++;
swap(arr[i], arr[j]); // Place the smaller element
at left

swap(arr[i + 1], arr[high]); // Place the pivot in its


correct position

return i + 1; // Return the partition index

void quicksort(int arr[], int low, int high)

if (low < high)

int pi = quick_partition(arr, low, high); // Partition


index

quicksort(arr, low, pi - 1); // Left subarray

quicksort(arr, pi + 1, high); // Right subarray

6. Implement a binary search algorithm to find a given element in a list.

int binar_search(int arr[], int l, int r, int x)

while (l <= r)

int mid = l + (r - l) / 2;

if (arr[mid] == x)
return mid;

else if (arr[mid] < x)

l = mid + 1;

else

r = mid - 1;

return -1;

Linked List:
1. Write a program to implement a linear linked list. The program should include
functions to insert a node at the beginning, at the end, and at a specified position.
Additionally, displays all the elements in the list.

#include <iostream>

using namespace std;

// Node structure

struct Node {

int data;

Node* next;

};

// Function to insert at the beginning

void insertAtBeginning(Node*& head, int data) {

Node* newNode = new Node{data, head};

head = newNode;

}
// Function to insert at the end

void insertAtEnd(Node*& head, int data) {

Node* newNode = new Node{data, nullptr};

if (!head) {

head = newNode;

return;

Node* temp = head;

while (temp->next) {

temp = temp->next;

temp->next = newNode;

// Function to insert at a specific position

void insertAtPosition(Node*& head, int data, int position) {

if (position == 0) {

insertAtBeginning(head, data);

return;

Node* newNode = new Node{data, nullptr};

Node* temp = head;

for (int i = 0; temp && i < position - 1; ++i) {

temp = temp->next;

if (!temp) {

cout << "Position out of range.\n";


delete newNode;

return;

newNode->next = temp->next;

temp->next = newNode;

// Function to display the list

void displayList(Node* head) {

while (head) {

cout << head->data << " -> ";

head = head->next;

cout << "NULL\n";

int main() {

Node* head = nullptr;

insertAtBeginning(head, 3);

insertAtEnd(head, 7);

insertAtPosition(head, 5, 1);

cout << "Linked List: ";

displayList(head);

return 0;

}
2. Write a program to reverse a linear linked list. The program should take a linked list
as input, reverse the order of its nodes, and output the reversed list.

#include <iostream>

using namespace std;

struct Node {

int data;

Node* next;

};

void insertAtEnd(Node*& head, int data) {

Node* newNode = new Node{data, nullptr};

if (!head) {

head = newNode;

return;

Node* temp = head;

while (temp->next) {

temp = temp->next;

temp->next = newNode;

void reverseList(Node*& head) {

Node *prev = nullptr, *curr = head, *next = nullptr;

while (curr) {

next = curr->next;

curr->next = prev;
prev = curr;

curr = next;

head = prev;

void displayList(Node* head) {

while (head) {

cout << head->data << " -> ";

head = head->next;

cout << "NULL\n";

int main() {

Node* head = nullptr;

insertAtEnd(head, 1);

insertAtEnd(head, 2);

insertAtEnd(head, 3);

cout << "Original List: ";

displayList(head);

reverseList(head);

cout << "Reversed List: ";

displayList(head);
return 0;

3. Write a program to delete a node from a linear linked list; i.e., here, we shall not
consider the deletion process of the first node and the last node of the list.
Additionally, handle edge cases such as attempting to delete from an empty list or
deleting the head node.

#include <iostream>

using namespace std;

struct Node {

int data;

Node* next;

};

void insertAtEnd(Node*& head, int data) {

Node* newNode = new Node{data, nullptr};

if (!head) {

head = newNode;

return;

Node* temp = head;

while (temp->next) {

temp = temp->next;

temp->next = newNode;

}
void deleteNode(Node*& head, int position) {

if (!head) {

cout << "List is empty.\n";

return;

if (position == 0) {

Node* temp = head;

head = head->next;

delete temp;

return;

Node* temp = head;

for (int i = 0; temp && i < position - 1; ++i) {

temp = temp->next;

if (!temp || !temp->next) {

cout << "Position out of range.\n";

return;

Node* toDelete = temp->next;

temp->next = toDelete->next;

delete toDelete;

void displayList(Node* head) {

while (head) {

cout << head->data << " -> ";

head = head->next;
}

cout << "NULL\n";

int main() {

Node* head = nullptr;

insertAtEnd(head, 1);

insertAtEnd(head, 2);

insertAtEnd(head, 3);

cout << "Original List: ";

displayList(head);

deleteNode(head, 1);

cout << "After Deletion: ";

displayList(head);

return 0;

4. Write a program to search for an element from a linked list.

#include <iostream>

using namespace std;

struct Node {
int data;

Node* next;

};

void insertAtEnd(Node*& head, int data) {

Node* newNode = new Node{data, nullptr};

if (!head) {

head = newNode;

return;

Node* temp = head;

while (temp->next) {

temp = temp->next;

temp->next = newNode;

bool searchElement(Node* head, int key) {

while (head) {

if (head->data == key) return true;

head = head->next;

return false;

int main() {

Node* head = nullptr;


insertAtEnd(head, 1);

insertAtEnd(head, 2);

insertAtEnd(head, 3);

int key = 2;

if (searchElement(head, key)) {

cout << key << " found in the list.\n";

} else {

cout << key << " not found in the list.\n";

return 0;

5. Write a program to sort the elements (in ascending order) of a linked list.

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

struct Node {

int data;

Node* next;

};

void insertAtEnd(Node*& head, int data) {

Node* newNode = new Node{data, nullptr};


if (!head) {

head = newNode;

return;

Node* temp = head;

while (temp->next) {

temp = temp->next;

temp->next = newNode;

void sortList(Node*& head) {

vector<int> values;

Node* temp = head;

while (temp) {

values.push_back(temp->data);

temp = temp->next;

sort(values.begin(), values.end());

temp = head;

for (int val : values) {

temp->data = val;

temp = temp->next;

void displayList(Node* head) {

while (head) {
cout << head->data << " -> ";

head = head->next;

cout << "NULL\n";

int main() {

Node* head = nullptr;

insertAtEnd(head, 3);

insertAtEnd(head, 1);

insertAtEnd(head, 2);

cout << "Original List: ";

displayList(head);

sortList(head);

cout << "Sorted List: ";

displayList(head);

return 0;

6. Write a program to create a doubly linked list and display the data items (nodes).

#include <iostream>

using namespace std;


struct Node {

int data;

Node* next;

Node* prev;

};

void insertAtEnd(Node*& head, int data) {

Node* newNode = new Node{data, nullptr, nullptr};

if (!head) {

head = newNode;

return;

Node* temp = head;

while (temp->next) {

temp = temp->next;

temp->next = newNode;

newNode->prev = temp;

void displayList(Node* head) {

while (head) {

cout << head->data << " <-> ";

head = head->next;

cout << "NULL\n";

}
int main() {

Node* head = nullptr;

insertAtEnd(head, 1);

insertAtEnd(head, 2);

insertAtEnd(head, 3);

cout << "Doubly Linked List: ";

displayList(head);

return 0;

Stack and Queue:


1. Write a program to implement a stack using arrays. Include functions for pushing an
element onto the stack, popping an element from the stack, and checking if the stack
is empty or full.

#include <iostream>

using namespace std;

class Stack {

int* arr;

int top;

int capacity;

public:
Stack(int size) {

arr = new int[size];

capacity = size;

top = -1;

~Stack() {

delete[] arr;

void push(int x) {

if (top == capacity - 1) {

cout << "Stack Overflow\n";

return;

arr[++top] = x;

int pop() {

if (top == -1) {

cout << "Stack Underflow\n";

return -1;

return arr[top--];

int peek() {

if (top == -1) {
cout << "Stack is empty\n";

return -1;

return arr[top];

bool isEmpty() {

return top == -1;

};

int main() {

Stack stack(5);

stack.push(10);

stack.push(20);

stack.push(30);

cout << "Top element: " << stack.peek() << endl;

stack.pop();

cout << "After popping, top element: " << stack.peek() << endl;

return 0;

}
2. Write a program to check if a given expression has balanced parentheses using a
stack. The program should support different types of parentheses: (), {}, and [].

#include <iostream>

#include <stack>

using namespace std;

bool isBalanced(string expr) {

stack<char> s;

for (char ch : expr) {

if (ch == '(' || ch == '{' || ch == '[') {

s.push(ch);

} else if (ch == ')' || ch == '}' || ch == ']') {

if (s.empty()) return false;

char top = s.top();

s.pop();

if ((ch == ')' && top != '(') ||

(ch == '}' && top != '{') ||

(ch == ']' && top != '[')) {

return false;

return s.empty();

int main() {

string expression = "{[()]}";


if (isBalanced(expression)) {

cout << "The expression is balanced.\n";

} else {

cout << "The expression is not balanced.\n";

return 0;

3. Write a program to implement a linked list-based stack and perform push and pop
operations.

#include <iostream>

using namespace std;

struct Node {

int data;

Node* next;

};

class Stack {

Node* top;

public:

Stack() : top(nullptr) {}

void push(int x) {

Node* newNode = new Node{x, top};

top = newNode;
}

int pop() {

if (!top) {

cout << "Stack Underflow\n";

return -1;

int data = top->data;

Node* temp = top;

top = top->next;

delete temp;

return data;

int peek() {

if (!top) {

cout << "Stack is empty\n";

return -1;

return top->data;

bool isEmpty() {

return top == nullptr;

};

int main() {
Stack stack;

stack.push(10);

stack.push(20);

stack.push(30);

cout << "Top element: " << stack.peek() << endl;

stack.pop();

cout << "After popping, top element: " << stack.peek() << endl;

return 0;

4. Write a program to convert an infix expression to a postfix expression using a stack.


The program should handle different operators and parentheses.

#include <iostream>

#include <stack>

using namespace std;

// Function to check operator precedence

int precedence(char op) {

if (op == '+' || op == '-') return 1;

if (op == '*' || op == '/') return 2;

return 0;

// Function to convert infix to postfix


string infixToPostfix(string infix) {

stack<char> s;

string postfix = "";

for (char ch : infix) {

if (isalnum(ch)) {

postfix += ch; // Add operands directly to postfix

} else if (ch == '(') {

s.push(ch);

} else if (ch == ')') {

while (!s.empty() && s.top() != '(') {

postfix += s.top();

s.pop();

s.pop(); // Pop '('

} else {

while (!s.empty() && precedence(s.top()) >= precedence(ch)) {

postfix += s.top();

s.pop();

s.push(ch);

while (!s.empty()) {

postfix += s.top();

s.pop();

}
return postfix;

int main() {

string infix = "a+b*(c^d-e)^(f+g*h)-i";

cout << "Infix Expression: " << infix << endl;

cout << "Postfix Expression: " << infixToPostfix(infix) << endl;

return 0;

5. Write a program to implement a queue (array or linked list-based). Also, delete a


given element from the queue.

#include <iostream>

using namespace std;

class Queue {

int* arr;

int front, rear, capacity, count;

public:

Queue(int size) {

arr = new int[size];

capacity = size;

front = 0;

rear = -1;
count = 0;

~Queue() {

delete[] arr;

void enqueue(int x) {

if (count == capacity) {

cout << "Queue Overflow\n";

return;

rear = (rear + 1) % capacity;

arr[rear] = x;

count++;

int dequeue() {

if (count == 0) {

cout << "Queue Underflow\n";

return -1;

int data = arr[front];

front = (front + 1) % capacity;

count--;

return data;

}
int peek() {

if (count == 0) {

cout << "Queue is empty\n";

return -1;

return arr[front];

bool isEmpty() {

return count == 0;

};

int main() {

Queue queue(5);

queue.enqueue(10);

queue.enqueue(20);

queue.enqueue(30);

cout << "Front element: " << queue.peek() << endl;

queue.dequeue();

cout << "After dequeuing, front element: " << queue.peek() << endl;

return 0;

}
Tree and Graph:
1. Write a program to create a tree. Include functions to traverse the tree in in-order,
pre-order, and post-order.
2. Write a program to implement a binary search tree; in addition, traverse the tree in in-
order, pre-order, and post-order.
3. Write a program to find the height of a binary tree (MAX or MIN).
4. Write a program to perform breadth-first search (BFS) on a graph.
5. Write a program to perform depth-first search (DFS) on a graph.

You might also like