0% found this document useful (0 votes)
23 views82 pages

Practical No - 01: B.Sc. Computer Science 2Nd Semester 2024-25 Nep Based

The document outlines practical programming exercises for a B.Sc. Computer Science course, focusing on C++ programming. It includes coding examples and algorithms for tasks such as adding two numbers, finding the largest number, calculating factorials, performing arithmetic operations, multiplying matrices, and storing book and employee information using structures and unions. Each practical exercise is accompanied by a coding section, algorithm, and expected output.

Uploaded by

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

Practical No - 01: B.Sc. Computer Science 2Nd Semester 2024-25 Nep Based

The document outlines practical programming exercises for a B.Sc. Computer Science course, focusing on C++ programming. It includes coding examples and algorithms for tasks such as adding two numbers, finding the largest number, calculating factorials, performing arithmetic operations, multiplying matrices, and storing book and employee information using structures and unions. Each practical exercise is accompanied by a coding section, algorithm, and expected output.

Uploaded by

mbeg1362
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 82

B.SC.

COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

PRACTICAL NO – 01
“WAP in C++ for addition of two numbers using float data type”
Coding :-
#include<iostream.h>

#include<conio.h>

void main()

float a,b,c;

clrscr();

cout << "Enter first no = \n";

cin >> a;

cout << "Enter second no = \n";

cin >> b;

c=a+b;

cout << "the sum is = " << c;

getch();

Algorithm :-
1. **Start**

2. **Declare** three float variables: `a`, `b`, and `c`.

3. **Clear the screen** (using `clrscr()`).

4. **Prompt the user** to enter the first number.

5. **Read** the first number into variable `a`.

6. **Prompt the user** to enter the second number.

7. **Read** the second number into variable `b`.

8. **Calculate** the sum of `a` and `b` and store it in `c`.

9. **Display** the result stored in `c`.

10. **Wait** for a key press (using `getch()`).

11. **End**

BY : Mohsin Beg [REGULAR(DSC)] Page 1


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

Output :-

BY : Mohsin Beg [REGULAR(DSC)] Page 2


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

PRACTICAL NO – 02
“WAP in C++ to find the biggest number between two numbers”
Coding :-
#include<iostream.h>

#include<conio.h>

void main()

int a,b;

cout<<"\n enter a";

cin>>a;

cout<<"\n enter b";

cin>>b;

if (a>b)

cout<< "\n a is big";

else

cout<<"\n b is big";

getch();

Algorithm :-
1. **Start**

2. **Declare** two integer variables: `a` and `b`.

3. **Prompt the user** to enter the value of `a`.

4. **Read** the value of `a`.

5. **Prompt the user** to enter the value of `b`.

6. **Read** the value of `b`.

7. **Compare** `a` and `b`:

BY : Mohsin Beg [REGULAR(DSC)] Page 3


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
* If `a > b`, **display** "a is big".

* Else, **display** "b is big".

8. **Wait** for a key press (`getch()`).

9. **End**

Output :-

BY : Mohsin Beg [REGULAR(DSC)] Page 4


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

PRACTICAL NO – 03
“WAP in C++ to find the factorial value of any entered number using
do-while loop.”
Coding :-
#include<iostream.h>

#include<conio.h>

void main()

int num,fact =1,i=1;

clrscr();

cout << "enter a number:";

cin >> num;

do

fact *= i;

i++;

while (i<=num);

cout << "factorial of "<<num<<" is:"<< fact;

getch();

Algorithm :-
1. **Start**

2. **Declare** three integer variables: `num`, `fact = 1`, and `i = 1`.

3. **Clear the screen** (`clrscr()`).

4. **Prompt the user** to enter a number.

5. **Read** the value into `num`.

6. **Repeat** the following steps **while** `i <= num`:

* Multiply `fact` by `i`.

* Increment `i` by 1.

BY : Mohsin Beg [REGULAR(DSC)] Page 5


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
7. **Display** the factorial of the number stored in `fact`.

8. **Wait** for a key press (`getch()`).

9. **End**

Output :-

BY : Mohsin Beg [REGULAR(DSC)] Page 6


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

PRACTICAL NO – 04
“WAP in C++ for various arithmetic operations using switch case
statements.”
Coding :-
#include <iostream.h>

#include <conio.h>

void main()

clrscr();

int a, b;

char op;

cout << "Enter first number: ";

cin >> a;

cout << "Enter second number: ";

cin >> b;

cout << "Enter operator (+, -, *, /, %): ";

cin >> op;

switch (op) {

case '+':

cout << "Result: " << (a + b);

break;

case '-':

cout << "Result: " << (a - b);

break;

case '*':

cout << "Result: " << (a * b);

break;

case '/':

cout << "Result: " << (a / b);

break;

BY : Mohsin Beg [REGULAR(DSC)] Page 7


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
case '%':

cout << "Result: " << (a % b);

break;

default:

cout << "Invalid operator!";

getch();

Algorithm :-
1. **Start**

2. **Declare** two integer variables: `a` and `b`, and one character variable: `op`.

3. **Clear the screen** (`clrscr()`).

4. **Prompt the user** to enter the first number.

5. **Read** the value into `a`.

6. **Prompt the user** to enter the second number.

7. **Read** the value into `b`.

8. **Prompt the user** to enter an operator (`+`, `-`, `*`, `/`, `%`).

9. **Read** the operator into `op`.

10. **Use a switch-case** to perform the operation based on the value of `op`:

* If `op` is `'+'`, **display** `a + b`.

* If `op` is `'-'`, **display** `a - b`.

* If `op` is `'*'`, **display** `a * b`.

* If `op` is `'/'`, **display** `a / b`.

* If `op` is `'%'`, **display** `a % b`.

* If `op` is none of the above, **display** "Invalid operator".

11. **Wait** for a key press (`getch()`).

12. **End**

Output :- (P.T.O.)

BY : Mohsin Beg [REGULAR(DSC)] Page 8


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

BY : Mohsin Beg [REGULAR(DSC)] Page 9


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

PRACTICAL NO – 05
“WAP in C++ for multiplication of two 3*3 matrices.”
Coding :-
#include <iostream.h>

#include <conio.h>

void main()

int a[3][3], b[3][3], c[3][3];

int i, j, k;

clrscr();

cout << "Enter elements of first 3x3 matrix:\n";

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

for (j = 0; j < 3; j++)

cin >> a[i][j];

cout << "Enter elements of second 3x3 matrix:\n";

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

for (j = 0; j < 3; j++)

cin >> b[i][j];

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

for (j = 0; j < 3; j++) {

c[i][j] = 0;

for (k = 0; k < 3; k++)

c[i][j] += a[i][k] * b[k][j];

cout << "Product of the two matrices is:\n";

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

for (j = 0; j < 3; j++)

cout << c[i][j] << " ";

cout << "\n";

BY : Mohsin Beg [REGULAR(DSC)] Page 10


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
getch();

Algorithm :-
1. **Start**

2. **Declare** three 3x3 matrices: `a[3][3]`, `b[3][3]`, and `c[3][3]`.

3. **Declare** loop control variables: `i`, `j`, `k`.

4. **Clear the screen** (`clrscr()`).

5. **Prompt the user** to enter elements of the first 3x3 matrix.

6. **Read** the values into matrix `a`.

7. **Prompt the user** to enter elements of the second 3x3 matrix.

8. **Read** the values into matrix `b`.

9. **Initialize and calculate** the product matrix `c` using:

* For each row `i` from 0 to 2:

* For each column `j` from 0 to 2:

* Set `c[i][j] = 0`

* For `k` from 0 to 2:

* Multiply `a[i][k]` with `b[k][j]` and add to `c[i][j]`

10. **Display** the resulting matrix `c` as the product of the two matrices.

11. **Wait** for a key press (`getch()`).

12. **End**

Output :-

BY : Mohsin Beg [REGULAR(DSC)] Page 11


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

PRACTICAL NO – 06
“WAP in C++ to store information of five books using structure.”
Coding :-
#include<iostream.h>

#include<conio.h>

#include<stdio.h>

struct Book

int id;

char title[50];

char author[50];

float price;

};

void main()

clrscr();

Book b[5];

int i;

cout << "Enter information for 5 books:\n";

for(i = 0; i < 5; i++)

cout << "\nBook " << i + 1 << ":\n";

cout << "Enter ID: ";

cin >> b[i].id;

fflush(stdin);

cout << "Enter Title: ";

gets(b[i].title);

cout << "Enter Author: ";

gets(b[i].author);

cout << "Enter Price: ";

cin >> b[i].price;


BY : Mohsin Beg [REGULAR(DSC)] Page 12
B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
}

clrscr();

cout << "Book Details:\n";

for(i = 0; i < 5; i++)

cout << "\nBook " << i + 1 << ":\n";

cout << "ID: " << b[i].id << "\n";

cout << "Title: " << b[i].title << "\n";

cout << "Author: " << b[i].author << "\n";

cout << "Price: " << b[i].price << "\n";

getch();

Algorithm :-
1. **Start**

2. **Define a structure** named `Book` with the following members:

* `int id`

* `char title[50]`

* `char author[50]`

* `float price`

3. **Declare** an array `b[5]` of type `Book`.

4. **Declare** a loop variable `i`.

5. **Clear the screen** (`clrscr()`).

6. **For** each book from `i = 0` to `4`:

* Prompt and **read** the book’s ID (`b*i+.id`).

* Clear the input buffer (`fflush(stdin)`).

* Prompt and **read** the book’s title using `gets(b*i+.title)`.

* Prompt and **read** the book’s author using `gets(b*i+.author)`.

* Prompt and **read** the book’s price (`b*i+.price`).

7. **Clear the screen** again.

8. **Display** the details of all 5 books using a loop from `i = 0` to `4`:

BY : Mohsin Beg [REGULAR(DSC)] Page 13


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
* Show the ID, Title, Author, and Price for each book.

9. **Wait** for a key press (`getch()`).

10. **End**

Output :-

BY : Mohsin Beg [REGULAR(DSC)] Page 14


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

PRACTICAL NO – 07
“WAP in C++ to store six employee information using union.”
Coding :-
#include <iostream.h>

#include <conio.h>

union Info

float salary;

};

struct Employee

char name[20];

Info data;

};

int main()

clrscr();

Employee emp[6];

int i;

for (i = 0; i < 6; i++)

cout << "\nEnter information for Employee " << i + 1 << ":";

cout << "\nEnter Name: ";

cin >> emp[i].name;

cout << "Enter Salary: ";

cin >> emp[i].data.salary;

cout << "\n\n--- Employee Information ---\n";

for (i = 0; i < 6; i++)

BY : Mohsin Beg [REGULAR(DSC)] Page 15


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
cout << "\nEmployee " << i + 1 << ":";

cout << "\nName: " << emp[i].name;

cout << "\nSalary: " << emp[i].data.salary;

getch();

return 0;

Algorithm :-
1. **Start**

2. **Define a union** named `Info` with one member:

* `float salary`

3. **Define a structure** named `Employee` with the following members:

* `char name[20]`

* `Info data` (union)

4. **Declare** an array `emp[6]` of type `Employee`.

5. **Declare** loop control variable `i`.

6. **Clear the screen** (`clrscr()`).

7. **For** each employee from `i = 0` to `5`:

* Prompt and **read** the employee’s name (`emp[i].name`).

* Prompt and **read** the employee’s salary (`emp[i].data.salary`).

8. **Display** a heading: "--- Employee Information ---".

9. **For** each employee from `i = 0` to `5`:

* Display the employee number, name, and salary.

10. **Wait** for a key press (`getch()`).

11. **End**

Output :- (P.T.O.)

BY : Mohsin Beg [REGULAR(DSC)] Page 16


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

BY : Mohsin Beg [REGULAR(DSC)] Page 17


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

PRACTICAL NO – 08
“WAP in C++ to calculate simple interest using call by value and call
by reference method.”
8.1) Using Call by Value method :-
Coding :-
#include <iostream.h>

#include <conio.h>

float si(float p, float r, float t)

return (p * r * t) / 100;

void main()

clrscr();

float p, r, t;

cout << "Enter Principal: ";

cin >> p;

cout << "Enter Rate: ";

cin >> r;

cout << "Enter Time: ";

cin >> t;

cout << "\nSimple Interest = " << si(p, r, t);

getch();

Algorithm :-
1. **Start**

2. **Define a function** `si(p, r, t)` that returns the simple interest using the formula:

S.I. = (P*R*T)/100

3. **In the main function**, declare float variables: `p`, `r`, and `t`.

BY : Mohsin Beg [REGULAR(DSC)] Page 18


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
4. **Clear the screen** (`clrscr()`).

5. **Prompt the user** to enter the Principal (`p`).

6. **Read** the value into `p`.

7. **Prompt the user** to enter the Rate of interest (`r`).

8. **Read** the value into `r`.

9. **Prompt the user** to enter the Time period (`t`).

10. **Read** the value into `t`.

11. **Call the function** `si(p, r, t)` to calculate simple interest.

12. **Display** the result returned by the function.

13. **Wait** for a key press (`getch()`).

14. **End**

Output :-

BY : Mohsin Beg [REGULAR(DSC)] Page 19


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

8.2) Using Call by Reference method :-


Coding :-
#include <iostream.h>

#include <conio.h>

void si(float p, float r, float t, float &result)

result = (p * r * t) / 100;

void main()

clrscr();

float p, r, t, interest;

cout << "Enter Principal: ";

cin >> p;

cout << "Enter Rate: ";

cin >> r;

cout << "Enter Time: ";

cin >> t;

si(p, r, t, interest);

cout << "\nSimple Interest = " << interest;

getch();

Algorithm :-
1. **Start**

2. Input principal amount `P`

3. Input rate of interest `R`

4. Input time period `T`

5. Calculate simple interest using formula:

**SI = (P × R × T) / 100**

6. Display the result (Simple Interest)

7. **End**

BY : Mohsin Beg [REGULAR(DSC)] Page 20


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

Output :-

BY : Mohsin Beg [REGULAR(DSC)] Page 21


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

PRACTICAL NO – 09
“WAP in C++ to find the sum and average of five numbers using
class and object.”
Coding :-
#include<iostream.h>

#include<conio.h>

class NumberOperations

private:

int num1, num2, num3, num4, num5;

int sum;

float average;

public:

void input()

cout << "Enter five numbers:\n";

cin >> num1 >> num2 >> num3 >> num4 >> num5;

void calculate()

sum = num1 + num2 + num3 + num4 + num5;

average = sum / 5.0;

void display()

cout << "Sum = " << sum << "\n";

cout << "Average = " << average << "\n";

};

void main()

BY : Mohsin Beg [REGULAR(DSC)] Page 22


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
{

clrscr();

NumberOperations obj;

obj.input();

obj.calculate();

obj.display();

getch();

Algorithm :-
1. **Start**

2. Create an object of class `NumberOperations`

3. Input five numbers from the user

4. Calculate the **sum** of the five numbers

5. Calculate the **average** as `sum / 5.0`

6. Display the **sum** and **average**

7. **End**

Output :-

BY : Mohsin Beg [REGULAR(DSC)] Page 23


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

PRACTICAL NO – 10
“WAP in C++ to multiply two numbers using private and public
member function.”
Coding :-
#include<iostream.h>

#include<conio.h>

class Multiply

private:

int a, b;

int mul()

return a * b;

public:

void getData()

cout << "Enter first number: ";

cin >> a;

cout << "Enter second number: ";

cin >> b;

void displayResult() {

int result = mul();

cout << "Multiplication of " << a << " and " << b << " is: " << result;

};

void main()

clrscr();

BY : Mohsin Beg [REGULAR(DSC)] Page 24


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
Multiply m;

m.getData();

m.displayResult();

getch();

Algorithm :-
1. **Start**

2. Create an object of class `Multiply`

3. Input two integers from the user

4. Multiply the two numbers using a private function

5. Display the multiplication result

Output :-

BY : Mohsin Beg [REGULAR(DSC)] Page 25


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

PRACTICAL NO – 11
“WAP in C++ to print structure like this using scope resolution
operator.”
1
12
123
1234
12345

Coding :-
#include <iostream.h>

#include <conio.h>

class Pattern

public:

static void display();

};

void Pattern::display()

int i, j;

for(i = 1; i <= 5; i++)

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

cout << j << " ";

cout << "\n";

BY : Mohsin Beg [REGULAR(DSC)] Page 26


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
int main()

clrscr();

Pattern::display();

getch();

return 0;

Algorithm :-
1. **Start**

2. Create a class `Pattern` with a static function `display()`

3. In `display()` function:

* Use a loop from `i = 1` to `5`

* For each `i`, print numbers from `1` to `i`

* Print a newline after each row

4. Call `Pattern::display()` from `main()`

5. **End**

Output :-

BY : Mohsin Beg [REGULAR(DSC)] Page 27


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

PRACTICAL NO – 12
“WAP in C++ for Constructor and Destructor.”
Coding :-
#include<iostream.h>

#include<conio.h>

class Demo

public:

Demo()

cout << "Constructor is called. Object created.";

~Demo()

cout << "Destructor is called. Object destroyed.";

};

void main() {

clrscr();

Demo d;

getch();

Algorithm :-
1. **Start**

2. Define a class `Demo` with:

* A **constructor** that prints a message when an object is created

* A **destructor** that prints a message when an object is destroyed

3. In `main()`:

* Clear screen (`clrscr()`)

* Create an object `d` of class `Demo` → Constructor is automatically called

BY : Mohsin Beg [REGULAR(DSC)] Page 28


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
* Wait for key press (`getch()`)

* Upon exiting `main()`, destructor is automatically called

4. **End**.

Output :-

BY : Mohsin Beg [REGULAR(DSC)] Page 29


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

PRACTICAL NO – 13

“WAP in C++ for multiple Inheritance.”


Coding :-
#include <iostream.h>

#include <conio.h>

class A

public:

void showA()

cout << "This is class A" << endl;

};

class B {

public:

void showB()

cout << "This is class B" << endl;

};

class C : public A, public B

public:

void showC()

cout << "This is class C (Derived from A and B)" << endl;

};

void main()

BY : Mohsin Beg [REGULAR(DSC)] Page 30


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
clrscr();

C obj;

obj.showA();

obj.showB();

obj.showC();

getch();

Algorithm :-
1. **Start**

2. Define **class A**:

* Inside class A, define a member function `showA()` that displays a message.

3. Define **class B**:

* Inside class B, define a member function `showB()` that displays a message.

4. Define **class C** that inherits **both class A and class B** publicly.

* Inside class C, define a member function `showC()` that displays a message.

5. In the **main() function**:

* Create an object `obj` of class `C`.

* Call the `showA()` function using the object to display class A's message.

* Call the `showB()` function using the object to display class B's message.

* Call the `showC()` function using the object to display class C's message.

6. **End**

Output :-

BY : Mohsin Beg [REGULAR(DSC)] Page 31


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

PRACTICAL NO – 14

“WAP in C++ for operator overloading.”


Coding :-
#include <iostream.h>

#include <conio.h>

class Complex

int real, imag;

public:

void getData()

cout << "Enter real and imaginary parts: ";

cin >> real >> imag;

void display()

cout << "Result = " << real << " + " << imag << "i" << endl;

Complex operator + (Complex c)

Complex temp;

temp.real = real + c.real;

temp.imag = imag + c.imag;

return temp;

};

void main() {

clrscr();

Complex c1, c2, c3;

BY : Mohsin Beg [REGULAR(DSC)] Page 32


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
c1.getData();

c2.getData();

c3 = c1 + c2; // Using overloaded + operator

c3.display();

getch();

Algorithm :-
1. **Start**

2. Define a class named **`Complex`** to represent complex numbers.

3. Inside the class, declare two integer variables: `real` and `imag`.

4. Define a function `getData()` to:

* Prompt the user to enter values for `real` and `imag`.

* Store the values in the respective variables.

5. Define a function `display()` to:

* Print the complex number in the format: `real + imag i`.

6. Overload the **`+` operator** using the function `operator+()`:

* Pass another `Complex` object as a parameter.

* Create a temporary object.

* Add real parts and imaginary parts separately.

* Return the temporary object.

7. In the `main()` function:

* Create three `Complex` class objects: `c1`, `c2`, and `c3`.

* Use `getData()` to input values into `c1` and `c2`.

* Add `c1` and `c2` using the overloaded `+` operator and store the result in `c3`.

* Call `display()` to show the result.

8. **End**

BY : Mohsin Beg [REGULAR(DSC)] Page 33


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

Output :-

BY : Mohsin Beg [REGULAR(DSC)] Page 34


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

PRACTICAL NO – 15
“WAP in C++ for friend class and friend function.”
Coding :-
#include <iostream.h>

#include <conio.h>

class A; // Forward declaration

class B {

public:

void show(A); // Member function to access A's private data

};

class A {

private:

int x;

public:

A() { x = 10; }

friend void B::show(A); // Make B's show() a friend

};

void B::show(A a) {

cout << "Value of x from class A: " << a.x << endl;

void main() {

clrscr();

A obj;

B b;

b.show(obj);

getch();

Algorithm :-
1. **Start**

2. Define **class A** with a private variable and constructor to assign a value.

BY : Mohsin Beg [REGULAR(DSC)] Page 35


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
3. Define **class B** with a member function `show()`.

4. Declare `B::show()` as a **friend** of class A.

5. In `show()`, access and display the private variable of class A.

6. In `main()`, create objects of class A and B.

7. Call `show()` using object of B and pass object of A.

8. **End**

Output :-

BY : Mohsin Beg [REGULAR(DSC)] Page 36


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

PRACTICAL NO – 16
“Write a program in C++ for virtual function and virtual class.”
Coding :-
#include <iostream.h>

#include <conio.h>

class A

public:

virtual void show()

cout << "Class A\n";

};

class B : virtual public A

public:

void show()

cout << "Class B\n";

};

void main()

clrscr();

A *ptr;

B obj;

ptr = &obj;

ptr->show();

getch();

BY : Mohsin Beg [REGULAR(DSC)] Page 37


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

Algorithm :-
1. **Start**

2. Define class `A` with a **virtual function** `show()`.

3. Define class `B` that **virtually inherits** from class `A`.

4. Override the `show()` function in class `B`.

5. In `main()`:

* Create a base class pointer `ptr`.

* Create an object `obj` of class `B`.

* Assign address of `obj` to `ptr`.

* Call `ptr->show()` (this will call class `B`'s function).

6. **End**

Output :-

BY : Mohsin Beg [REGULAR(DSC)] Page 38


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

PRACTICAL NO – 17
“Write a program in C++ for Exception Handling.”
Coding :-
#include <iostream.h>

#include <conio.h>

void main()

clrscr();

int a, b;

cout << "Enter two numbers: ";

cin >> a >> b;

try

if (b == 0)

throw "Division by zero!";

cout << "Result: " << a / b << "\n";

} catch (const char *msg) {

cout << "Error: " << msg << "\n";

getch();

Algorithm :-
1. **Start**

2. Declare two integer variables `a` and `b`.

3. Ask the user to input values for `a` and `b`.

4. Use a `try` block:

* If `b` is 0, **throw** an exception (e.g., "Division by zero!").

* Otherwise, perform division and display the result.

5. Use a `catch` block to **handle** the exception and display an error message.

6. **End**

BY : Mohsin Beg [REGULAR(DSC)] Page 39


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

PRACTICAL NO – 18
“Write a program in C++ to open and close a file using file Handling.”
Coding :-
#include <fstream.h>

#include <conio.h>

void main()

clrscr();

ofstream fout;

fout.open("test.txt");

if (fout)

fout << "Hello, this is a test file.";

cout << "File opened and written successfully.\n";

} else

cout << "Failed to open the file.\n";

fout.close();

cout << "File closed.\n";

getch();

Algorithm :-
1. **Start**

2. Declare an `ofstream` object for file output.

3. Use the `open()` function to create or open a file named `"test.txt"`.

4. Check if the file opened successfully:

* If yes, write a message into the file.

* If not, display an error message.

5. Close the file using the `close()` function.

6. Display a message that the file is closed.

BY : Mohsin Beg [REGULAR(DSC)] Page 40


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
7. **End**

Output :-

BY : Mohsin Beg [REGULAR(DSC)] Page 41


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

PRACTICAL NO – 19
“Given two ordered arrays of integers, write a program to merge the
two-arrays to get an ordered array.”
Coding :-
#include <iostream.h>

#include <conio.h>

void main()

clrscr();

int arr1[] = {1, 4, 7};

int arr2[] = {2, 3, 6};

int m = 3, n = 3;

int merged[m + n];

int i = 0, j = 0, k = 0;

while (i < m && j < n)

if (arr1[i] < arr2[j]) merged[k++] = arr1[i++];

else merged[k++] = arr2[j++];

while (i < m) merged[k++] = arr1[i++];

while (j < n) merged[k++] = arr2[j++];

for (int i = 0; i < m + n; i++) cout << merged[i] << " ";

getch();

Algorithm :-
1. **Start**

2. Initialize two pointers `i` and `j` to 0, which will point to the current elements of both arrays.

3. Create an empty `merged[]` array to store the merged result.

4. Compare the elements at `arr1[i]` and `arr2[j]`:

* If `arr1[i]` is smaller, add `arr1[i]` to `merged[]` and increment `i`.

* If `arr2[j]` is smaller, add `arr2[j]` to `merged[]` and increment `j`.


BY : Mohsin Beg [REGULAR(DSC)] Page 42
B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
5. If any elements are left in `arr1[]`, add them to `merged[]`.

6. If any elements are left in `arr2[]`, add them to `merged[]`.

7. Print the merged array.

8. **End**

Output :-

BY : Mohsin Beg [REGULAR(DSC)] Page 43


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

PRACTICAL NO – 20
“WAP to display Fibonacci series (i) using recursion, (ii) using
iteration.”
Coding :-
#include <iostream.h>

#include <conio.h>

int fibonacci(int n)

if (n <= 1)

return n;

return fibonacci(n - 1) + fibonacci(n - 2);

void main()

clrscr();

int n;

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

cin >> n;

cout << "Fibonacci series using recursion: ";

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

cout << fibonacci(i) << " ";

getch();

Algorithm :-
✅ Algorithm for Fibonacci Series Using Recursion**

1. **Start**

2. Define a function `fibonacci(n)`:

* If `n` is 0 or 1, return `n` (Base Case).


BY : Mohsin Beg [REGULAR(DSC)] Page 44
B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
* Otherwise, return the sum of `fibonacci(n-1)` and `fibonacci(n-2)` (Recursive Case).

3. Read the value `n` (number of terms) from the user.

4. For each `i` from 0 to `n-1`, call the `fibonacci(i)` function and print the result.

5. **End**

✅ Algorithm for Fibonacci Series Using Iteration**

1. **Start**

2. Read the value `n` (number of terms) from the user.

3. Initialize `a = 0` and `b = 1` (the first two terms of the Fibonacci series).

4. Print the first term `a` (if `n > 0`), then print the second term `b` (if `n > 1`).

5. For each `i` from 2 to `n-1`

* Calculate the next Fibonacci number as `next = a + b`.

* Print the next Fibonacci number.

* Update `a = b` and `b = next` for the next iteration.

6. **End**

Output :-

BY : Mohsin Beg [REGULAR(DSC)] Page 45


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

PRACTICAL NO – 21
“WAP to calculate Factorial of a number (i) using recursion, (ii)
using iteration.”
(i) using recursion :
Coding :-
#include <iostream.h>

#include <conio.h>

int factorial(int n)

if (n == 0 || n == 1)

return 1;

return n * factorial(n - 1);

void main()

clrscr();

int num;

cout << "Enter a number: ";

cin >> num;

cout << "Factorial using recursion: " << factorial(num);

getch();

Algorithm :-
1. **Start**

2. Read an integer `n` from the user.

3. Define a function `factorial(n)`:

* If `n == 0` or `n == 1`, return 1.

* Else return `n * factorial(n - 1)`.

BY : Mohsin Beg [REGULAR(DSC)] Page 46


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
4. Call the function `factorial(n)` and store the result.

5. Display the result.

6. **End**

Output :-

(ii) using iteration :


Coding :-
#include <iostream.h>

#include <conio.h>

void main()

clrscr(); int n, i;

long factorial = 1;

cout << "Enter a positive integer: ";

cin >> n;

if (n < 0) {

cout << "Factorial is not defined for negative numbers.";

} else {

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

factorial = factorial * i;

cout << "Factorial of " << n << " = " << factorial;

getch();

Algorithm :-
1. Start

BY : Mohsin Beg [REGULAR(DSC)] Page 47


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
2. Declare variables `n`, `i`, and `factorial`

3. Set `factorial = 1`

4. Read the value of `n`

5. If `n < 0`, then

a. Display "Factorial is not defined for negative numbers"

b. Go to step 9

6. Repeat the loop from `i = 1` to `n`

a. Multiply `factorial = factorial * i`

7. End of loop

8. Display "Factorial of n = factorial"

9. Stop

Output :-

BY : Mohsin Beg [REGULAR(DSC)] Page 48


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

PRACTICAL NO – 22
“WAP to calculate GCD of two numbers (i) with recursion (ii)
without recursion”
(i) with recursion :
Coding :-
#include <iostream.h>

#include <conio.h>

int a, b;

int gcd()

if (b == 0)

return a;

else {

int temp = b;

b = a % b;

a = temp;

return gcd();

void main()

clrscr();

cout << "Enter first number: ";

cin >> a;

cout << "Enter second number: ";

cin >> b;

int result = gcd();

cout << "GCD of the numbers is: " << result;

getch();

BY : Mohsin Beg [REGULAR(DSC)] Page 49


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

Algorithm :-
1. Start

2. Declare global variables `a`, `b`

3. Read two integers `a` and `b` from the user

4. Call the recursive function `gcd()`

5. Inside `gcd()` function:

a. If `b == 0`, return `a`

b. Else:

i. Set `temp = b`

ii. Set `b = a % b`

iii. Set `a = temp`

iv. Call `gcd()` again

6. Store the returned result

7. Display the GCD

8. Stop

Output :-

(ii) without recursion :


Coding :-
#include <iostream.h>

#include <conio.h>

void main()

clrscr();

int a, b, temp;

cout << "Enter first number: ";

cin >> a;

BY : Mohsin Beg [REGULAR(DSC)] Page 50


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
cout << "Enter second number: ";

cin >> b;

while (b != 0) {

temp = b;

b = a % b;

a = temp;

cout << "GCD of the numbers is: " << a;

getch();

Algorithm :-
1. Start

2. Declare variables `a`, `b`, and `temp`

3. Read two integers `a` and `b` from the user

4. Repeat the following steps while `b ≠ 0`:

a. Set `temp = b`

b. Set `b = a % b`

c. Set `a = temp`

5. When the loop ends, `a` contains the GCD

6. Display the value of `a` as the GCD

7. Stop

Output :-

BY : Mohsin Beg [REGULAR(DSC)] Page 51


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

PRACTICAL NO – 23
“Create a Matrix class using templates. Write a menu-driven
program to perform following Matrix Operations (2-D array
implementation): a) Sum b) Difference c) Product d) Transpose 22.
Create the Person class. Create some objects of this class (by taking
information from the user). Inherit the class Person to create two
classes Teacher and Student class. Maintain the respective
information in the classes and create, display and delete objects of
these two classes (Use Runtime Polymorphism).”

✅ Part 1: Matrix Operations using Template :


Coding :-
#include <iostream.h>

#include <conio.h>

#define MAX 10

class Matrix

int a[MAX][MAX];

int r, c;

public:

void read()

cout << "\nEnter number of rows and columns: ";

cin >> r >> c;

cout << "Enter elements:\n";

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

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

BY : Mohsin Beg [REGULAR(DSC)] Page 52


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
cout << "Element [" << i << "][" << j << "]: ";

cin >> a[i][j];

void show()

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

for (int j = 0; j < c; j++)

cout << a[i][j] << "\t";

cout << "\n";

Matrix add(Matrix m)

Matrix res;

if (r != m.r || c != m.c)

cout << "Addition not possible!\n";

res.r = res.c = 0;

return res;

res.r = r;

res.c = c;

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

for (int j = 0; j < c; j++)

res.a[i][j] = a[i][j] + m.a[i][j];

return res;

Matrix sub(Matrix m)

Matrix res;

BY : Mohsin Beg [REGULAR(DSC)] Page 53


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
if (r != m.r || c != m.c)

cout << "Subtraction not possible!\n";

res.r = res.c = 0;

return res;

res.r = r;

res.c = c;

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

for (int j = 0; j < c; j++)

res.a[i][j] = a[i][j] - m.a[i][j];

return res;

Matrix mul(Matrix m)

Matrix res;

if (c != m.r)

cout << "Multiplication not possible!\n";

res.r = res.c = 0;

return res;

res.r = r;

res.c = m.c;

for (int i = 0; i < res.r; i++)

for (int j = 0; j < res.c; j++) {

res.a[i][j] = 0;

for (int k = 0; k < c; k++)

res.a[i][j] += a[i][k] * m.a[k][j];

return res;

BY : Mohsin Beg [REGULAR(DSC)] Page 54


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
Matrix trans()

Matrix res;

res.r = c;

res.c = r;

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

for (int j = 0; j < c; j++)

res.a[j][i] = a[i][j];

return res;

};

void main() {

clrscr();

Matrix m1, m2, res;

int choice;

cout << "Enter Matrix 1:\n";

m1.read();

cout << "\nEnter Matrix 2:\n";

m2.read();

do

cout << "\n===== MATRIX MENU =====\n";

cout << "1. Addition\n";

cout << "2. Subtraction\n";

cout << "3. Multiplication\n";

cout << "4. Transpose of Matrix 1\n";

cout << "5. Exit\n";

cout << "Enter your choice: ";

cin >> choice;

switch (choice)

BY : Mohsin Beg [REGULAR(DSC)] Page 55


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
{

case 1:

res = m1.add(m2);

cout << "Result of Addition:\n";

res.show();

break;

case 2:

res = m1.sub(m2);

cout << "Result of Subtraction:\n";

res.show();

break;

case 3:

res = m1.mul(m2);

cout << "Result of Multiplication:\n";

res.show();

break;

case 4:

res = m1.trans();

cout << "Transpose of Matrix 1:\n";

res.show();

break;

case 5:

cout << "Exiting Program...\n";

break;

default:

cout << "Invalid choice. Try again.\n";

} while (choice != 5);

getch();

BY : Mohsin Beg [REGULAR(DSC)] Page 56


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

Algorithm :-
1. **Start**

2. Declare a `Matrix` class with:

* 2D array `a[MAX][MAX]`

* Integers `r` and `c` for rows and columns

* Member functions: `read()`, `show()`, `add()`, `sub()`, `mul()`, `trans()`

3. In `main()` function:

1. Clear the screen using `clrscr()`

2. Declare three `Matrix` objects: `m1`, `m2`, and `res`

3. Read elements of `m1` and `m2` using `read()` function

4. Display menu and repeat until user selects **Exit**:

* **Option 1**: Add `m1` and `m2` using `add()`, store in `res`, display using `show()`

* **Option 2**: Subtract `m2` from `m1` using `sub()`, store in `res`, display using `show()`

* **Option 3**: Multiply `m1` and `m2` using `mul()`, store in `res`, display using `show()`

* **Option 4**: Transpose `m1` using `trans()`, store in `res`, display using `show()`

* **Option 5**: Exit the loop

* If invalid choice, show error message

5. **End**

Output :-

BY : Mohsin Beg [REGULAR(DSC)] Page 57


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

✅ Part 2: Inheritance with Runtime Polymorphism (Person, Teacher,


Student) :
Coding :-
#include <iostream.h>

#include <conio.h>

#include <string.h>

class Person {

protected:

char name[30];

int age;

public:

virtual void input() {

cout << "Enter Name: ";

cin >> name;

cout << "Enter Age: ";

cin >> age;

virtual void display() {

BY : Mohsin Beg [REGULAR(DSC)] Page 58


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
cout << "Name: " << name << "\n";

cout << "Age: " << age << "\n";

virtual ~Person() {

cout << "Person object deleted.\n";

};

class Teacher : public Person {

char subject[30];

public:

void input() {

Person::input();

cout << "Enter Subject: ";

cin >> subject;

void display() {

Person::display();

cout << "Subject: " << subject << "\n";

~Teacher() {

cout << "Teacher object deleted.\n";

};

class Student : public Person {

int roll;

char course[30];

public:

void input() {

Person::input();

cout << "Enter Roll Number: ";

cin >> roll;

cout << "Enter Course: ";

BY : Mohsin Beg [REGULAR(DSC)] Page 59


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
cin >> course;

void display() {

Person::display();

cout << "Roll Number: " << roll << "\n";

cout << "Course: " << course << "\n";

~Student() {

cout << "Student object deleted.\n";

};

void main() {

clrscr();

Person *p;

int ch;

do {

cout << "\n=== PERSON MENU ===\n";

cout << "1. Create Teacher\n2. Create Student\n3. Exit\n";

cout << "Enter your choice: ";

cin >> ch;

switch (ch) {

case 1:

p = new Teacher;

p->input();

cout << "\n--- Displaying Teacher Info ---\n";

p->display();

delete p;

break;

case 2:

p = new Student;

p->input();

cout << "\n--- Displaying Student Info ---\n";

BY : Mohsin Beg [REGULAR(DSC)] Page 60


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
p->display();

delete p;

break;

case 3:

cout << "Exiting...\n";

break;

default:

cout << "Invalid choice!\n";

} while (ch != 3);

getch();

Algorithm :-
1. **Start**

2. **Define class `Person`** with:

* Data members: `name`, `age`

* Virtual functions:

* `input()` to take name and age

* `display()` to display name and age

* Virtual destructor

3. **Define class `Teacher` inheriting from `Person`** with:

* Data member: `subject`

* Override functions:

* `input()` → call `Person::input()` and take subject

* `display()` → call `Person::display()` and show subject

* Destructor to show delete message

4. **Define class `Student` inheriting from `Person`** with:

* Data members: `roll`, `course`

* Override functions:

* `input()` → call `Person::input()` and take roll number and course

* `display()` → call `Person::display()` and show roll and course

* Destructor to show delete message

BY : Mohsin Beg [REGULAR(DSC)] Page 61


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
5. **In `main()` function:**

* Clear the screen

* Declare a base class pointer `p`

* Declare a variable `ch` for choice

6. **Repeat until user chooses to exit (do-while loop):**

* Display menu:

1. Create Teacher

2. Create Student

3. Exit

* Get user choice in `ch`

7. **Switch on choice `ch`:**

* **Case 1 (Teacher):**

* Create a `Teacher` object using `new`

* Call `input()` using pointer `p`

* Call `display()` to show teacher info

* Delete object to free memory

* **Case 2 (Student):**

* Create a `Student` object using `new`

* Call `input()` using pointer `p`

* Call `display()` to show student info

* Delete object to free memory

* **Case 3 (Exit):**

* Display exit message

* **Default:**

* Show invalid choice message

8. Wait for user key press using `getch()`

9. **End**

BY : Mohsin Beg [REGULAR(DSC)] Page 62


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

Output :-

BY : Mohsin Beg [REGULAR(DSC)] Page 63


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

PRACTICAL NO – 24
“Create a class Triangle. Include overloaded functions for
calculating area. Overload assignment operator and equality
operator.”
Coding :-
#include <iostream.h>

#include <conio.h>

#include <math.h>

class Triangle {

float a, b, c, h;

public:

void set1() {

// set base and height

a = 10; h = 5;

b = c = 0;

void set2() {

// set 3 sides

a = 3; b = 4; c = 5;

h = 0;

float area() {

if (h != 0)

return 0.5 * a * h;

float s = (a + b + c) / 2;

return sqrt(s * (s - a) * (s - b) * (s - c));

Triangle operator=(Triangle t) {

a = t.a; b = t.b; c = t.c; h = t.h;

return *this;

BY : Mohsin Beg [REGULAR(DSC)] Page 64


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
}

int operator==(Triangle t) {

return (a == t.a && b == t.b && c == t.c && h == t.h);

void show() {

cout << "Area = " << area() << "\n";

};

void main() {

clrscr();

Triangle t1, t2, t3;

t1.set1(); // base & height

t2.set2(); // 3 sides

t3 = t1;

cout << "Triangle t1: "; t1.show();

cout << "Triangle t2: "; t2.show();

cout << "Triangle t3 (copy of t1): "; t3.show();

if (t1 == t3)

cout << "t1 and t3 are equal\n";

else

cout << "t1 and t3 are not equal\n";

getch();

Algorithm :-
1. **Start**

2. **Define class `Triangle`** with variables: `a`, `b`, `c`, `h`.

3. Inside class:

* `set1()` → Assign base `a = 10`, height `h = 5`, and `b = c = 0`.

* `set2()` → Assign 3 sides: `a = 3`, `b = 4`, `c = 5`, and `h = 0`.

* `area()` → Calculate:

* If `h ≠ 0`, use: `0.5 × a × h`

* Else, use Heron’s formula.

BY : Mohsin Beg [REGULAR(DSC)] Page 65


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
* Overload `=` to copy triangle values.

* Overload `==` to compare two triangles.

* `show()` → Display area.

4. In `main()`:

* Create objects `t1`, `t2`, `t3`.

* Call `t1.set1()` and `t2.set2()`.

* Assign `t3 = t1`.

* Display areas using `show()`.

* Compare `t1 == t3` and show result.

5. **End**

Output :-

BY : Mohsin Beg [REGULAR(DSC)] Page 66


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

PRACTICAL NO – 25
“Create a class Box containing length, breadth and height. Include
following methods in it: a) Calculate surface Area b) Calculate
Volume c) Increment, Overload ++ operator (both prefix and
postfix) d) Decrement, Overload – operator (both prefix and
postfix) e) Overload operator == (to check equality of two boxes),
as a friend function f) Overload Assignment operator g) Check if it
is a Cube or cuboid.”

Coding :-
#include <iostream.h>

#include <conio.h>

class Box {

int length, breadth, height;

public:

// Set values

void set(int l, int b, int h) {

length = l;

breadth = b;

height = h;

// Calculate surface area

int surfaceArea() {

return 2 * (length * breadth + breadth * height + height * length);

// Calculate volume

int volume() {

return length * breadth * height;

}
BY : Mohsin Beg [REGULAR(DSC)] Page 67
B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
// Check if it's a cube

void checkShape() {

if (length == breadth && breadth == height)

cout << "It is a Cube.\n";

else

cout << "It is a Cuboid.\n";

// Prefix ++

Box operator++() {

++length;

++breadth;

++height;

return *this;

// Postfix ++

Box operator++(int) {

Box temp = *this;

length++;

breadth++;

height++;

return temp;

// Prefix --

Box operator--() {

--length;

--breadth;

--height;

return *this;

// Postfix --

Box operator--(int) {

Box temp = *this;

BY : Mohsin Beg [REGULAR(DSC)] Page 68


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
length--;

breadth--;

height--;

return temp;

// Assignment operator

Box operator=(Box b) {

length = b.length;

breadth = b.breadth;

height = b.height;

return *this;

// Friend function for equality check

friend int operator==(Box b1, Box b2);

// Display values

void show() {

cout << "Length = " << length << ", Breadth = " << breadth << ", Height = " << height << "\n";

cout << "Surface Area = " << surfaceArea() << "\n";

cout << "Volume = " << volume() << "\n";

};

// Friend function definition

int operator==(Box b1, Box b2) {

return (b1.length == b2.length && b1.breadth == b2.breadth && b1.height == b2.height);

void main() {

clrscr();

Box b1, b2, b3;

b1.set(3, 3, 3);

b2.set(4, 5, 6);

cout << "Box 1:\n";

b1.show();

BY : Mohsin Beg [REGULAR(DSC)] Page 69


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
b1.checkShape();

cout << "\nBox 2:\n";

b2.show();

b2.checkShape();

// Assignment

b3 = b1;

cout << "\nBox 3 (copy of Box 1):\n";

b3.show();

// Equality check

if (b1 == b3)

cout << "Box 1 and Box 3 are equal.\n";

else

cout << "Box 1 and Box 3 are not equal.\n";

// Increment and Decrement

++b1;

b2++;

cout << "\nAfter increment:\n";

cout << "Box 1:\n"; b1.show();

cout << "Box 2:\n"; b2.show();

--b1;

b2--;

cout << "\nAfter decrement:\n";

cout << "Box 1:\n"; b1.show();

cout << "Box 2:\n"; b2.show();

getch();

Algorithm :-
1. **Start**

2. Define a `Box` class with:

* Private data members: `length`, `breadth`, `height`

* Public methods:

BY : Mohsin Beg [REGULAR(DSC)] Page 70


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
* `set()` – to set box dimensions

* `surfaceArea()` – to calculate surface area

* `volume()` – to calculate volume

* `checkShape()` – to check if the box is a cube or cuboid

* `show()` – to display box details

* Overloaded operators: `++`, `--`, `=`, `==`

3. In the `main()` function:

* Clear screen using `clrscr()`

* Create three `Box` objects: `b1`, `b2`, `b3`

* Set dimensions for `b1` and `b2` using `set()`

* Display details and shape of `b1` and `b2` using `show()` and `checkShape()`

* Assign `b1` to `b3` using overloaded `=` operator

* Display `b3` and check equality with `b1` using `==` operator

* Apply increment (`++`) and decrement (`--`) operators on `b1` and `b2`

* Display updated box details after each operation

4. **End **

Output :-

BY : Mohsin Beg [REGULAR(DSC)] Page 71


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

PRACTICAL NO – 26
“Create a structure Student containing fields for Roll No., Name
Class, Year and Total Marks. Create 10 students and store them in
a file.”
Coding :-
#include <iostream.h>

#include <conio.h>

#include <fstream.h> // For file operations

// Define the Student structure

struct Student {

int rollNo;

char name[50];

char className[10];

int year;

float totalMarks;

};

void main() {

clrscr();

Student s[10]; // Array to store 10 students

ofstream file("student.dat", ios::binary); // Open file for writing in binary mode

// Input data for 10 students

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

cout << "Enter details for Student " << i + 1 << ":\n";

cout << "Roll No.: ";

cin >> s[i].rollNo;

cout << "Name: ";

cin >> s[i].name;

cout << "Class: ";

cin >> s[i].className;

cout << "Year: ";

BY : Mohsin Beg [REGULAR(DSC)] Page 72


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
cin >> s[i].year;

cout << "Total Marks: ";

cin >> s[i].totalMarks;

file.write((char*)&s[i], sizeof(Student)); // Write structure to file

cout << "\n";

file.close(); // Close the file

cout << "Student data successfully stored in file 'student.dat'.";

getch();

Algorithm :-
1. **Start**

2. Define a `Student` structure with fields:

* Roll No.

* Name

* Class

* Year

* Total Marks

3. Declare an array to store data for 10 students.

4. Open a file (`student.dat`) in binary write mode.

5. Repeat for 10 students:

* Accept input for all fields of the student.

* Write the student record to the file.

6. Close the file.

7. Display message: "Data stored successfully."

8. **End**

Output :-

BY : Mohsin Beg [REGULAR(DSC)] Page 73


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

BY : Mohsin Beg [REGULAR(DSC)] Page 74


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

PRACTICAL NO – 27
“Write a program to retrieve the student information from the file
created in the previous question and print it in the following
format: Roll No. Name Marks.”
Coding :-
#include <iostream.h>

#include <conio.h>

#include <fstream.h> // For file operations

// Define the Student structure (same as used when writing to file)

struct Student {

int rollNo;

char name[50];

char className[10];

int year;

float totalMarks;

};

void main() {

clrscr();

Student s;

ifstream file("student.dat", ios::binary); // Open file for reading in binary mode

if (!file) {

cout << "Error: File could not be opened!";

getch();

return;

cout << "Roll No.\tName\t\tMarks\n";

cout << "------------------------------------\n";

// Read and display each student record

while (file.read((char*)&s, sizeof(Student))) {

cout << s.rollNo << "\t\t" << s.name << "\t\t" << s.totalMarks << "\n";

BY : Mohsin Beg [REGULAR(DSC)] Page 75


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
}

file.close(); // Close the file

getch();

Algorithm :-
1. **Start**

2. Define the `Student` structure with fields:

* Roll No.

* Name

* Class

* Year

* Total Marks

3. Open the file `student.dat` in binary read mode.

4. If the file fails to open, display an error message and exit.

5. Display table headers: Roll No., Name, Marks.

6. While not end of file:

* Read a student record from the file.

* Display Roll No., Name, and Total Marks.

7. Close the file.

8. **End**

Output :-

BY : Mohsin Beg [REGULAR(DSC)] Page 76


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

PRACTICAL NO – 28
“Copy the contents of one text file to another file, after removing all
whitespaces.”
Coding :-
#include <fstream.h>

#include <conio.h>

void main() {

clrscr();

ifstream fin("input.txt");

ofstream fout("output.txt");

char ch;

while (fin.get(ch)) {

if (ch != ' ' && ch != '\n' && ch != '\t') {

fout.put(ch);

fin.close();

fout.close();

getch();

Algorithm :-
1. **Start**

2. Open `input.txt` in read mode.

3. Open `output.txt` in write mode.

4. Read each character from the input file one by one.

5. If the character is **not** a space `' '`, tab `'\t'`, or newline `'\n'`, write it to the output file.

6. Repeat until end of file.

7. Close both files.

8. **End**

BY : Mohsin Beg [REGULAR(DSC)] Page 77


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

PRACTICAL NO – 29
“Write a program for exception handling.”
Coding :-
#include <iostream.h>

#include <conio.h>

void divide() {

int a, b;

cout << "Enter numerator: ";

cin >> a;

cout << "Enter denominator: ";

cin >> b;

if (b == 0)

throw "Division by zero not allowed!";

else

cout << "Result = " << (a / b) << "\n";

void main() {

clrscr();

try {

divide();

catch (const char *msg) {

cout << "Error: " << msg << "\n";

getch();

Algorithm :-
1. **Start**

2. Define a function `divide()`:

* Inside the function, take two inputs: numerator and denominator.

BY : Mohsin Beg [REGULAR(DSC)] Page 78


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
* If the denominator is zero, **throw an exception** with the message

`"Division by zero not allowed!"`.

* If the denominator is not zero, **perform the division** and display the result.

3. In the `main()` function:

* **Call the `divide()` function** inside a `try` block.

* If an exception is thrown, **catch** it using the `catch` block an

**display the error message**.

4. **End**

BY : Mohsin Beg [REGULAR(DSC)] Page 79


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

PRACTICAL NO – 30
“Write a program to insert data into file and to display it.”
Coding :-
#include <iostream.h>

#include <fstream.h>

#include <conio.h>

void main() {

clrscr();

// Declare file stream objects

ofstream fout("data.txt"); // Open file in write mode

ifstream fin("data.txt"); // Open file in read mode

// Check if file opened successfully

if (!fout) {

cout << "Error opening file for writing.";

getch();

return;

// Insert data into the file

fout << "Hello, this is a sample data file.\n";

fout << "We are writing and reading from this file.\n";

fout << "This is the third line of data.\n";

fout.close(); // Close the output file stream

// Check if file opened successfully for reading

if (!fin) {

cout << "Error opening file for reading.";

getch();

return;

// Display the contents of the file

cout << "Contents of the file:\n";

BY : Mohsin Beg [REGULAR(DSC)] Page 80


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED
char ch;

while (fin.get(ch)) {

cout << ch;

fin.close(); // Close the input file stream

getch();

Algorithm :-
1. **Start the program.**

2. **Clear the screen.**

3. **Declare file stream objects:**

* Create an `ofstream` object `fout` to write to a file (`data.txt`).

* Create an `ifstream` object `fin` to read from the same file (`data.txt`).

4. **Check if the file opened successfully for writing (`fout`):**

* If not, display an error message and exit the program.

5. **Write sample data to the file (`data.txt`) using `fout`.**

6. **Close the output file stream (`fout`).**

7. **Check if the file opened successfully for reading (`fin`):**

* If not, display an error message and exit the program.

8. **Display the contents of the file (`data.txt`) using `fin`:**

* Read and display each character of the file until the end of the file is reached.

9. **Close the input file stream (`fin`).**

10. **Wait for user input before closing the program.**

11. **End the program.**

BY : Mohsin Beg [REGULAR(DSC)] Page 81


B.SC. COMPUTER SCIENCE 2ND SEMESTER 2024-25 NEP BASED

Output :-

BY : Mohsin Beg [REGULAR(DSC)] Page 82

You might also like