24213_Sarita File 1
24213_Sarita File 1
ROHTAK
PRACTICAL FILE
BASED ON
SOFTWARE LAB : 24MSCSCS202DS01
M.SC. COMPUTER SCIENCE
Submitted To : Submitted by :
Dr. Priti Sharma Sarita
Dr. Amrinder Kaur M.sc. Cs 2nd sem
Mr. Amit Dhaka Roll No. : 24213
1|Page
S.No. Program Page No.
1. Write a C program to declare and initialize an array, 3
then find and print the largest and smallest elements in
the array.
2. Write a C program to demonstrate basic data structure 4-6
operations such as creating, inserting, deleting, and
displaying elements in an array.
Write a C program to insert and delete an element at a 7-9
3. specified position in a linear array.
Write a C program to implement and demonstrate a 10
4. sequential search on an array.
Write a C program to implement and demonstrate a 11
5. binary search on a sorted array.
Write a C program to implement and demonstrate the 12
6. Bubble sort algorithm.
Write a C program to perform operations: push, pop, 13-14
7. and display.
Write a C program to implement a queue using an array 15-16
8. and perform basic queue operations: enqueue, dequeue,
and display.
Write a C program to implement and demonstrate the 17-18
9. Selection sort algorithm
Write a C program to implement and demonstrate the 19-20
10. Insertion sort algorithm.
Write a C program to implement and demonstrate the 21-22
11. Quick sort algorithm.
Write a C program to implement and demonstrate the 23-24
12. Merge sort algorithm.
Write a C program to implement a singly linked list and 25-27
13. perform insertion, deletion, and traversal operations.
Write a C program to implement a binary tree and 28-29
14. perform in-order, pre-order, and post-order traversal
using recursion.
Write a C program to implement a binary search tree 30-32
15. (BST) and perform insertion, deletion, and search
operations.
2|Pag e
1. Write a C program to declare and initialize an array, then find and print the
largest and smallest elements in the array.
#include <stdio.h>
int main() {
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter the elements: ");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int largest = arr[0];
int smallest = arr[0];
return 0;
}
Output
3|Pag e
2. Write a C program to demonstrate basic data structure operations such as
creating, inserting, deleting, and displaying elements in an array.
#include <stdio.h>
void display(int arr[], int n) {
if (n == 0) {
printf("Array is empty.\n");
} else {
printf("Array elements: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
}
4|Pag e
}
}
int main() {
int arr[100], n = 0, choice, element, position;
while (1) {
printf("\nMenu:\n");
printf("1. Insert element\n");
printf("2. Delete element\n");
printf("3. Display array\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter element to insert: ");
scanf("%d", &element);
printf("Enter position to insert (0 to %d): ", n);
scanf("%d", &position);
insert(arr, &n, element, position);
break;
case 2:
printf("Enter position to delete (0 to %d): ", n - 1);
scanf("%d", &position);
delete(arr, &n, position);
break;
case 3:
display(arr, n);
break;
case 4:
return 0;
default:
printf("Invalid choice! Please try again.\n");
}
}
return 0;
5|Pag e
}
Output
6|Pag e
3. Write a C program to insert and delete an element at a specified
position in a linear array.
#include <stdio.h>
7|Pag e
}
int main() {
int arr[100], n = 0, choice, element, position;
while (1) {
printf("\nMenu:\n");
printf("1. Insert element\n");
printf("2. Delete element\n");
printf("3. Display array\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter element to insert: ");
scanf("%d", &element);
printf("Enter position to insert (0 to %d): ", n);
scanf("%d", &position);
insert(arr, &n, element, position);
break;
case 2:
printf("Enter position to delete (0 to %d): ", n - 1);
scanf("%d", &position);
delete(arr, &n, position);
break;
case 3:
display(arr, n);
break;
case 4:
return 0;
default:
printf("Invalid choice! Please try again.\n");
}
}
return 0;
}
8|Pag e
Output
9|Pag e
4. Write a C program to implement and demonstrate a sequential search on
an array.
#include <stdio.h>
int sequentialSearch(int arr[], int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
return i;
}
}
return -1;
}
int main() {
int arr[] = {34, 78, 12, 56, 89, 23};
int n = sizeof(arr) / sizeof(arr[0]);
int key, result;
printf("Enter the element to search: ");
scanf("%d", &key);
return 0;
}
Output
10 | P a g e
5. Write a C program to implement and demonstrate a binary search on a sorted array.
#include <stdio.h>
int binarySearch(int arr[], int n, int key) {
int low = 0, high = n - 1, mid;
if (arr[mid] == key) {
return mid;
}
else if (arr[mid] < key) {
low = mid + 1;
}
else {
high = mid - 1;
}
}
return -1;
}
int main() {
int arr[] = {12, 23, 34, 45, 56, 67, 78, 89};
int n = sizeof(arr) / sizeof(arr[0]);
int key, result;
11 | P a g e
6. Write a C program to implement and demonstrate the Bubble sort algorithm.
#include <stdio.h>
bubbleSort(arr, n);
12 | P a g e
7. Write a C program to perform operations: push, pop, and display.
#include <stdio.h>
#include <stdlib.h>
#define MAX 5
struct Stack {
int arr[MAX];
int top;
};
void initStack(struct Stack* stack) {
stack->top = -1;
}
int isFull(struct Stack* stack) {
return stack->top == MAX - 1;
}
int isEmpty(struct Stack* stack) {
return stack->top == -1;
}
void push(struct Stack* stack, int value) {
if (isFull(stack)) {
printf("Stack Overflow\n");
} else {
stack->arr[++stack->top] = value;
}
}
void pop(struct Stack* stack) {
if (isEmpty(stack)) {
printf("Stack Underflow\n");
} else {
printf("%d popped from stack\n", stack->arr[stack->top--]);
}
}
13 | P a g e
}
}
int main() {
struct Stack stack;
initStack(&stack);
push(&stack, 2);
push(&stack, 6);
push(&stack, 5);
push(&stack, 3);
display(&stack);
pop(&stack);
display(&stack);
return 0;
}
Output
14 | P a g e
8. Write a C program to implement a queue using an array and perform basic
queue operations: enqueue, dequeue, and display.
#include <stdio.h>
#include <stdlib.h>
#define MAX 5
struct Queue {
int arr[MAX];
int front;
int rear;
};
void initQueue(struct Queue* queue) {
queue->front = -1;
queue->rear = -1;
}
int isFull(struct Queue* queue) {
return queue->rear == MAX - 1;
}
int isEmpty(struct Queue* queue) {
return queue->front == -1 || queue->front > queue->rear;
}
void enqueue(struct Queue* queue, int value) {
if (isFull(queue)) {
printf("Queue Overflow\n");
} else {
if (queue->front == -1) {
queue->front = 0;
}
queue->arr[++queue->rear] = value;
}
}
void dequeue(struct Queue* queue) {
if (isEmpty(queue)) {
printf("Queue Underflow\n");
} else {
printf("%d dequeued from queue\n", queue->arr[queue->front]);
queue->front++;
}
}
void display(struct Queue* queue) {
if (isEmpty(queue)) {
15 | P a g e
printf("Queue is empty\n");
} else {
printf("Queue elements: ");
for (int i = queue->front; i <= queue->rear; i++) {
printf("%d ", queue->arr[i]);
}
printf("\n");
}
}
int main() {
struct Queue queue;
initQueue(&queue);
enqueue(&queue, 10);
enqueue(&queue, 20);
enqueue(&queue, 30);
enqueue(&queue, 40);
enqueue(&queue, 50);
enqueue(&queue, 60);
display(&queue);
display(&queue);
enqueue(&queue, 60);
display(&queue);
return 0;
}
Output
16 | P a g e
9. Write a C program to implement and demonstrate the Selection sort
algorithm.
#include <stdio.h>
display(arr, n);
return 0;
17 | P a g e
}
Output
18 | P a g e
10. Write a C program to implement and demonstrate the
Insertion sort algorithm.
#include <stdio.h>
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
insertionSort(arr, n);
display(arr, n);
19 | P a g e
return 0;
}
Output
20 | P a g e
11. Write a C program to implement and demonstrate the Quick sort
algorithm.
#include <stdio.h>
int main() {
int arr[] = {64, 34, 25, 12, 22, 11};
21 | P a g e
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1);
display(arr, n);
return 0;
}
Output
22 | P a g e
12. Write a C program to implement and demonstrate the Merge sort
algorithm.
#include <stdio.h>
int i = 0, j = 0, k = left;
23 | P a g e
merge(arr, left, mid, right);
}
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);
mergeSort(arr, 0, n - 1);
display(arr, n);
return 0;
}
Output
24 | P a g e
13. Write a C program to implement a singly linked list and
perform insertion, deletion, and traversal operations.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
newNode->data = value;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
return;
}
last->next = newNode;
}
25 | P a g e
free(temp);
return;
}
if (temp == NULL) {
printf("Element not found\n");
return;
}
prev->next = temp->next;
free(temp);
}
int main() {
struct Node* head = NULL;
insertAtEnd(&head, 10);
insertAtEnd(&head, 20);
insertAtEnd(&head, 30);
insertAtBeginning(&head, 5);
26 | P a g e
deleteNode(&head, 20);
printf("After deleting 20: ");
traverseList(head);
return 0;
}
Output
27 | P a g e
14. Write a C program to implement a binary tree and perform in-
order, pre-order, and post-order traversal using recursion.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
28 | P a g e
}
int main() {
struct Node* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
root->right->left = createNode(6);
root->right->right = createNode(7);
return 0;
}
Output
29 | P a g e
15. Write a C program to implement a binary search tree (BST) and perform
insertion, deletion, and search operations.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->left = newNode->right = NULL;
return newNode;
}
return root;
}
30 | P a g e
struct Node* current = root;
while (current && current->left != NULL) {
current = current->left;
}
return current;
}
struct Node* delete(struct Node* root, int value) {
if (root == NULL) {
return root;
}
if (value < root->data) {
root->left = delete(root->left, value);
} else if (value > root->data) {
root->right = delete(root->right, value);
} else {
if (root->left == NULL) {
struct Node* temp = root->right;
free(root);
return temp;
} else if (root->right == NULL) {
struct Node* temp = root->left;
free(root);
return temp;
}
struct Node* temp = minNode(root->right);
root->data = temp->data;
root->right = delete(root->right, temp->data);
}
return root;
}
void inOrderTraversal(struct Node* root) {
if (root != NULL) {
inOrderTraversal(root->left);
printf("%d ", root->data);
inOrderTraversal(root->right);
}
}
int main() {
struct Node* root = NULL;
31 | P a g e
root = insert(root, 40);
root = insert(root, 70);
root = insert(root, 60);
root = insert(root, 80);
return 0;
}
Output
32 | P a g e
MAHARSHI DAYANAND UNIVERSITY,
ROHTAK
PRACTICAL FILE
BASED ON
SOFTWARE LAB : 24MSCSCS202DS02
M.SC. COMPUTER SCIENCE
Submitted To : Submitted by :
Dr. Priti Sharma Sarita
Dr. Amrinder Kaur M.sc. Cs 2nd sem
Mr. Amit Dhaka Roll No. : 24213
1|P age
S.No. Program Page No.
1. To understand and run basic UNIX/LINUX commands 3
2|P age
Basic Linux Commands:-
ls command in Linux
cd command in Linux
3|P age
echo command in Linux
4|P age
File Manipulation Commands: -
cp command of Linux .
mv command in Linux
rm command in Linux
5|P age
C Program Using system calls fork, exec, getpid, exit, wait
.
#include <stdio.h>
#include <string.h>
int main() {
// Simulate 'cp'
char source[] = "This is a test file.";
char destination[100];
strcpy(destination, source);
printf("Simulated cp:\n");
printf("Source Content: %s\n", source);
printf("Destination Content after copy: %s\n\n", destination);
// Simulate 'ls'
printf("Simulated ls:\n");
printf("main.c\nfile1.txt\nfile2.txt\nnotes.docx\nimage.png\n\n");
// Simulate 'grep'
char *lines[] = {
"This is a sample text file.",
"We are learning Linux commands.",
"grep is used to search text.",
"Enjoy coding in C.",
"Practice regularly for better understanding."
};
char keyword[] = "text";
return 0;
}
6|P age
7|P age
To write C Programs using the following system calls of Unix/Linux operating
system close, stat, opendir, readdir
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
struct stat fileStat;
int fd;
return 0;
}
8|P age
Output
9|P age
C Program to system call cp, ls, grep-
#include <stdio.h>
#include <string.h>
int main() {
// Simulate 'cp'
char source[] = "This is a test file.";
char destination[100];
strcpy(destination, source);
printf("Simulated cp:\n");
printf("Source Content: %s\n", source);
printf("Destination Content after copy: %s\n\n", destination);
// Simulate 'ls'
printf("Simulated ls:\n");
printf("main.c\nfile1.txt\nfile2.txt\nnotes.docx\nimage.png\n\n");
// Simulate 'grep'
char *lines[] = {
"This is a sample text file.",
"We are learning Linux commands.",
"grep is used to search text.",
"Enjoy coding in C.",
"Practice regularly for better understanding."
};
char keyword[] = "text";
return 0;
}
10 | P a g
e
11 | P a g
e
12 | P a g
e
Write a Shell program to check the given number is even or odd.
#!/bin/bash
number=7
13 | P a g
e
Write a shell program to check given year is leap year or not
#!/bin/bash
year=2024
14 | P a g
e
Shell Program to Find factorial-
#!/bin/bash
num=5
fact=1
15 | P a g e
Write a C Program for implementation of priority scheduling algorithms
#include <stdio.h>
int main() {
int n = 4, i, j;
int pid[] = {1, 2, 3, 4};
int bt[] = {10, 5, 8, 6};
int pr[] = {2, 1, 4, 3};
int wt[4], tat[4];
wt[0] = 0;
for(i = 1; i < n; i++)
wt[i] = bt[i-1] + wt[i-1];
printf("PID\tBT\tPR\tWT\tTAT\n");
for(i = 0; i < n; i++)
printf("P%d\t%d\t%d\t%d\t%d\n", pid[i], bt[i], pr[i], wt[i], tat[i]);
return 0;
}
16 | P a g e
OUTPUT
17 | P a g e
To write a C program for implementation of Round Robin scheduling algorithms
#include <stdio.h>
int main() {
int n = 4, tq = 3;
int bt[] = {5, 15, 4, 3};
int wt[4] = {0}, tat[4], rem_bt[4];
int i, time = 0;
while(1) {
int done = 1;
for(i = 0; i < n; i++) {
if(rem_bt[i] > 0) {
done = 0;
if(rem_bt[i] > tq) {
time += tq;
rem_bt[i] -= tq;
} else {
time += rem_bt[i];
wt[i] = time - bt[i];
rem_bt[i] = 0;
}
}
}
if(done) break;
}
printf("PID\tBT\tWT\tTAT\n");
for(i = 0; i < n; i++)
printf("P%d\t%d\t%d\t%d\n", i+1, bt[i], wt[i], tat[i]);
return 0;
}
18 | P a g e
OUTPUT
19 | P a g e
To write a C program for implementation of FCFS and SJF scheduling algorithms.
#include <stdio.h>
wt[0] = 0;
for (int i = 1; i < n; i++)
wt[i] = bt[i - 1] + wt[i - 1];
wt[0] = 0;
for (i = 1; i < n; i++)
wt[i] = wt[i - 1] + bt[i - 1];
Output
21 | P a g e
C Program to implement Producer-Consumer Problem Using Semaphores
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#define SIZE 5
int buffer[SIZE];
int in = 0, out = 0;
buffer[in] = item;
printf("Producer produced item %d at position %d\n", item, in);
in = (in + 1) % SIZE;
pthread_mutex_unlock(&mutex);
sem_post(&full);
sleep(1);
}
return NULL;
}
item = buffer[out];
printf("Consumer consumed item %d from position %d\n", item, out);
out = (out + 1) % SIZE;
pthread_mutex_unlock(&mutex);
sem_post(&empty);
sleep(2);
}
return NULL;
}
int main() {
pthread_t prod, cons;
22 | P a g e
sem_init(&empty, 0, SIZE);
sem_init(&full, 0, 0);
pthread_mutex_init(&mutex, NULL);
pthread_join(prod, NULL);
pthread_join(cons, NULL);
sem_destroy(&empty);
sem_destroy(&full);
pthread_mutex_destroy(&mutex);
return 0;
}
23 | P a g e
Output
24 | P a g e
C Program to Implement Banker,s Algorithm for Deadlock Avoidance
#include <stdio.h>
#define P 5 // Number of processes
#define R 3 // Number of resources
int main() {
int alloc[P][R] = { {0, 1, 0}, {2, 0, 0}, {3, 0, 2}, {2, 1, 1}, {0, 0, 2} };
int max[P][R] = { {7, 5, 3}, {3, 2, 2}, {9, 0, 2}, {2, 2, 2}, {4, 3, 3} };
int avail[R] = {3, 3, 2};
if (j == R) {
for (int k = 0; k < R; k++)
avail[k] += alloc[p][k];
safeSeq[count++] = p;
finish[p] = 1;
found = 1;
}
}
}
if (!found) {
printf("System is not in a safe state.\n");
return 0;
}
}
return 0;
}
25 | P a g e
Output
26 | P a g e
MAHARSHI DAYANAND UNIVERSITY,
ROHTAK
PRACTICAL FILE
BASED ON
SOFTWARE LAB : 24MSCSCS202DS03
M.SC. COMPUTER SCIENCE
Submitted To : Submitted by :
Dr. Priti Sharma Sarita
Dr. Amrinder Kaur M.sc. Cs 2nd sem
Mr. Amit Dhaka Roll No. : 24213
1|Page
S.No. Program Page No.
1. Write a C++ program to take two numbers as input from 3
the user and display their sum.
2. Write a C++ program to demonstrate decision-making 4
constructs like if-else and looping constructs like for and
while loops.
Write a C++ program to define a class called `Rectangle` 5
3. with attributes `length` and `width`, and display the area of
the rectangle.
Write a C++ program to demonstrate the concept of 6
4. inheritance by creating a base class `Shape` and derived
class `Rectangle`. Display the area of the rectangle using
inheritance.
Write a C++ program to define a class called `Student` with 7
5. attributes `name` and `roll number`. Use member functions
to input and display student details.
Write a C++ program to demonstrate the use of constructor 8
6. and destructor in a class.
Write a C++ program to showcase the use of access 9-10
7. specifiers (`public`, `private`, `protected`) in a class.
Write a C++ program to demonstrate function overloading 11
8. by defining multiple functions with the same name but
different parameters.
Write a C++ program to demonstrate dynamic 12
9. polymorphism using virtual functions.
Write a C++ program to demonstrate the working of friend 13
10. function.
.Write a C++ program to demonstrate the use of pointers to 14
11. objects. Define a class `Book` with attributes `title` and
`author`, and use pointers to access and display book
details.
Write a C++ program to handle exceptions using `try- 15
12. catch` blocks.
Write C++ code to implement a simple template function to 16
13. find the maximum of two numbers. Test the function with
different data types.
Write a C++ program to perform file input and output 17
14. operations, including opening, reading, writing, and closing
files.
Implement error handling during file operations in a C++ 18-19
15. program, including handling exceptions and error codes.
2|Page
1. Write a C++ program to take two numbers as input from the user and
display their sum.
#include <iostream>
using namespace std;
int main() {
double num1, num2, sum;
cout << "The sum of " << num1 << " and " << num2 << " is " << sum << sendl;
return 0;
}
3|Page
2. Write a C++ program to demonstrate decision-making constructs like if-
else and looping constructs like for and while loops.
#include <iostream>
using namespace std;
int main() {
int number;
if (number % 2 == 0) {
cout << number << " is even." << endl;
} else {
cout << number << " is odd." << endl;
}
cout << "\nCounting from 1 to 5 using for loop:" << endl;
for (int i = 1; i <= 5; i++) {
cout << i << " ";
}
cout << "\n\nCounting down from 5 to 1 using while loop:" << endl;
int count = 5;
while (count >= 1) {
cout << count << " ";
count--;
}
4|Page
3. Write a C++ program to define a class called `Rectangle` with attributes
`length` and `width`, and display the area of the rectangle.
#include <iostream>
using namespace std;
class Rectangle{
public :
int length, width;
void get(){
cout<<"Enter length and width of Rectangle :";
cin>>length>>width;
}
void area(){
cout<<"Area of Rectangle = "<<length*width;
}
};
int main() {
Rectangle r;
r.get();
r.area();
return 0;
}
5|Page
4. Write a C++ program to demonstrate the concept of inheritance by
creating a base class `Shape` and derived class `Rectangle`. Display the
area of the rectangle using inheritance.
#include <iostream>
using namespace std;
class Shape {
protected:
double length;
double width;
public:
void set(double l, double w) {
length = l;
width = w;
}
};
class Rectangle : public Shape {
public:
double getArea() {
return length * width;
}
};
int main() {
Rectangle rect;
int l, w;
rect.set(l, w);
cout<< "Area of the rectangle: "<< rect.getArea()<<endl;
return 0;
}
6|Page
5. Write a C++ program to define a class called `Student` with attributes
`name` and `roll number`. Use member functions to input and display
student details.
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
string name;
int rollNumber;
public:
void inputDetails() {
cout << "Enter name: ";
getline(cin, name);
return 0;
}
7|Page
6. Write a C++ program to demonstrate the use of constructor and
destructor in a class.
#include <iostream>
using namespace std;
class Demo {
public:
Demo() {
cout << "Constructor called" << endl;
}
~Demo() {
cout << "Destructor called" << endl;
}
void display() {
cout << "Hello from display function" << endl;
}
};
int main() {
Demo obj;
obj.display();
return 0;
}
8|Page
7. Writea C++ program to showcase the use of access specifiers (`public`,
`private`, `protected`) in a class.
#include <iostream>
using namespace std;
class A {
private:
int privateVar;
protected:
int protectedVar;
public:
int publicVar;
A() {
privateVar = 1;
protectedVar = 2;
publicVar = 3;
}
void show() {
cout << "Private Variable: " << privateVar << endl;
cout << "Protected Variable: " << protectedVar << endl;
cout << "Public Variable: " << publicVar << endl;
}
};
class B : public A {
public:
void showDerivedAccess() {
// cout << privateVar << endl; // Not accessible
cout << "Protected Variable (from Derived): " << protectedVar << endl;
cout << "Public Variable (from Derived): " << publicVar << endl;
}
};
int main() {
B Obj;
Obj.show();
9|Page
Obj.showDerivedAccess();
cout << "Accessing public variable from main: " << Obj.publicVar << endl;
return 0;
}
10 | P a g e
8. Write a C++ program to demonstrate function overloading by defining
multiple functions with the same name but different parameters.
#include <iostream>
using namespace std;
class Calculator {
public:
void add(int a, int b) {
cout << "Sum of two integers: " << a + b << endl;
}
int main() {
Calculator calc;
calc.add(5, 10);
calc.add(3.5, 2.5);
calc.add(1, 2, 3);
return 0;
}
11 | P a g e
9. Write a C++ program to demonstrate dynamic polymorphism using virtual
functions.
#include <iostream>
using namespace std;
class Animal {
public:
virtual void sound() {
cout << "Animal makes a sound" << endl;
}
};
class Dog : public Animal {
public:
void sound() override {
cout << "Dog barks" << endl;
}
};
class Cat : public Animal {
public:
void sound() override {
cout << "Cat meows" << endl;
}
};
int main() {
Animal* animal;
Dog dog;
Cat cat;
animal = &dog;
animal->sound();
animal = &cat;
animal->sound();
return 0;
}
12 | P a g e
10. Write a C++ program to demonstrate the working of friend function.
#include <iostream>
using namespace std;
class Box {
private:
int length;
public:
Box() {
length = 0;
}
void setLength(int l) {
length = l;
}
void printLength(Box b) {
cout << "Length of box: " << b.length << endl;
}
int main() {
Box box;
box.setLength(15);
printLength(box);
return 0;
}
13 | P a g e
11. Write a C++ program to demonstrate the use of pointers to objects.
Define a class `Book` with attributes `title` and `author`, and use pointers
to access and display book details.
#include <iostream>
using namespace std;
class Book {
public:
string title;
string author;
void display() {
cout << "Title: " << title << endl;
cout << "Author: " << author << endl;
}
};
int main() {
Book book1;
Book* ptr;
ptr = &book1;
return 0;
}
14 | P a g e
12. Write a C++ program to handle exceptions using `try-catch` blocks.
#include <iostream>
using namespace std;
int main() {
int a, b;
cout << "Enter two integers (a and b): ";
cin >> a >> b;
try {
if (b == 0) {
throw "Division by zero is not allowed.";
}
cout << "Result: " << a / b << endl;
}
catch (const char* msg) {
cout << "Exception caught: " << msg << endl;
}
return 0;
}
15 | P a g e
13. Write C++ code to implement a simple template function to find the
maximum of two numbers. Test the function with different data types.
#include <iostream>
using namespace std;
int main() {
cout << "Max of 10 and 20: " << getMax(10, 20) << endl;
cout << "Max of 3.5 and 2.7: " << getMax(3.5, 2.7) << endl;
cout << "Max of 'A' and 'Z': " << getMax('A', 'Z') << endl;
cout << "Max of \"Apple\" and \"Banana\": " << getMax(string("Apple"), string("Banana")) <<
endl;
return 0;
}
16 | P a g e
14. Write a C++ program to perform file input and output operations,
including opening, reading, writing, and closing files.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outFile("sample.txt");
if (outFile.is_open()) {
outFile << "Hello, world!\n";
outFile << "File operations in C++.\n";
outFile.close();
} else {
cout << "Error: Cannot create file for writing." << endl;
return 1;
}
ifstream inFile("sample.txt");
if (inFile.is_open()) {
string line;
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
} else {
cout << "Error: Cannot open file for reading." << endl;
return 1;
}
return 0;
}
17 | P a g e
15. Implement error handling during file operations in a C++ program,
including handling exceptions and error codes.
#include <iostream>
#include <fstream>
#include <stdexcept> // for exceptions
using namespace std;
int main() {
const char* filename = "sample.txt";
ofstream outFile;
try {
outFile.open(filename, ios::out);
if (!outFile) {
throw runtime_error("Error opening file for writing");
}
if (outFile.is_open()) {
throw runtime_error("Error closing the file after writing.");
}
ifstream inFile(filename);
if (!inFile) {
throw runtime_error("Error opening file for reading.");
}
string line;
while (getline(inFile, line)) {
cout << line << endl; // Print each line
}
inFile.close(); // Close the file after reading
if (inFile.is_open()) {
18 | P a g e
throw runtime_error("Error closing the file after reading.");
}
}
catch (const ios_base::failure& e) {
cerr << "File I/O error: " << e.what() << endl;
}
catch (const runtime_error& e) {
cerr << "Runtime error: " << e.what() << endl;
}
catch (const exception& e) {
cerr << "Unexpected error: " << e.what() << endl;
}
return 0;
}
19 | P a g e