Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
9 views21 pages

Core Practical Programs

Uploaded by

varunvarun171512
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)
9 views21 pages

Core Practical Programs

Uploaded by

varunvarun171512
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/ 21

2nd SEMESTER CORE PRACTICAL PROGRAMS

DATA STRUCTURES AND C++

1) Implement classes and objects


2) Implement the concept of Polymorphism
3) Demonstrate Inheritance
4) Implement File Operations
5) Implement the concept of Exception handling
6) Demonstrate Virtual Functions
7) Implement Stack concept
8) Implement Queue concept
9) Implement Sorting
10) Implement Binary Searching
11) Implement Traversal Algorithm
12) Implement a Linked List

1) AIM: Create a C++ program to find volume of sphere using classes and objects

ALGORITHM:
STEP 1-> Start the program

STEP 2-> Include necessary header files ‘iostream’ and ‘cmath’

STEP 3-> Define a new class ‘Sphere’

- constructor ‘Sphere(double r)’ to initialize the radius

- ‘getRadius()’ function to get the radius from the user

- ‘calculateVolume()’ function to calculate the volume of the sphere

STEP 4-> Implement the main function:

- declare the variable ‘radius’

- prompt the user to input the radius of the sphere

- calculate the volume of the sphere using appropriate member functions.

STEP 5-> Display the calculated volume.

STEP 6->Stop the program.

PROGRAM:
#include <iostream>
#include <cmath>
using namespace std;

class Sphere {
private:
double radius;

public:
Sphere(double r) : radius(r) {}

double getRadius() const {


return radius;
}

double calculateVolume() const {


return (4.0 / 3.0) * M_PI * pow(radius, 3);
}
};

int main() {
double radius;
cout << "Enter the radius of the sphere: ";
cin >> radius;

Sphere sphere(radius);

cout << "Volume of the sphere with radius " << sphere.getRadius() << " is: " <<
sphere.calculateVolume() << endl;

return 0;
}

OUTPUT:
Enter the radius of the sphere: 2.5
Volume of the sphere with radius 2.5 is: 65.4498

_______________________________________________________________________________________________________
2) AIM:Create a C++ program to multiply values, get the values from the user using polymorphism

ALGORITHM:
STEP 1-> Start the program

STEP 2-> Include necessary header files ‘iostream’.

STEP 3-> Define a new class ‘Multiplier’ with a member function :

- ‘multiply()’ : declared as a virtual function to multiply the values

STEP 4-> Define a class ‘CustomMultiplier’ inherited publicly from ‘Multiplier’ with a
member function

- ‘multiply()’ : to multiply the values

STEP 5-> Implement the main() function


- prompt the user to input two values to multiply

- multiply the two values using appropriate member functions

STEP 6-> Stop the program

PROGRAM:
#include <iostream>
class Multiplier {
public:
virtual int multiply(int a, int b) const {
return a * b;
}
};

class CustomMultiplier : public Multiplier {


public:
int multiply(int a, int b) const override {
int result = 0;
for (int i = 0; i < a; ++i) {
result += b;
}
return result;
}
};

int main() {
Multiplier* multiplier1 = new Multiplier();
Multiplier* multiplier2 = new CustomMultiplier();

int num1 , num2;


std::cout<<"Enter 2 values : ";
std::cin>>num1>>num2;
std::cout << "Multiplication using base class: " << multiplier1->multiply(num1, num2) <<
std::endl;
std::cout << "Multiplication using derived class: " << multiplier2->multiply(num1, num2) <<
std::endl;
delete multiplier1;
delete multiplier2;
return 0;
}

OUTPUT:
Enter 2 values : 5 2
Multiplication using base class: 10
Multiplication using derived class: 10

_______________________________________________________________________________________________________
3) AIM:Create a C++ program to display Bike details by using inheritance

ALGORITHM:
STEP 1-> Start the program

STEP 2-> Include the necessary header files ‘iostream’ and ‘string’

STEP 3-> Define a new class ‘Vehicle'

- protected data members ‘brand’,’model’ and ‘year’

- constructor Vehicle(string model,stringbrand,int year) to get the details of the vehicle

- displayDetails() functions to display the details

STEP 4-> Implement the main() function

- create an object ‘myBike’ of type ‘Bike’

- call ‘displayBikeDetails()’ function to display the bike details

STEP 5-> Stop the program

PROGRAM:
#include <iostream>
#include <string>
using namespace std;
class Vehicle {
protected:
string brand;
string model;
int year;

public:
Vehicle(string brand, string model, int year)
: brand(brand), model(model), year(year) {}

void displayDetails() {
cout << "Brand: " << brand << endl;
cout << "Model: " << model << endl;
cout << "Year: " << year << endl;
}
};

class Bike : public Vehicle {


private:
int horsepower;

public:
Bike(string brand, string model, int year, int horsepower)
: Vehicle(brand, model, year), horsepower(horsepower) {}
void displayBikeDetails() {
displayDetails();
cout << "Horse Power: " << horsepower << endl;
}
};

int main() {
Bike myBike("YAMAHA", "RX135", 1995, 14 );

cout << "Bike Details:" << endl;


myBike.displayBikeDetails();

return 0;
}
OUTPUT:
Bike Details:
Brand: YAMAHA
Model: RX135
Year: 1995
Horse Power: 14
_______________________________________________________________________________________________________

4) AIM:Create a C++ program to create file by implementing file operation

ALGORITHM:
STEP 1->Start the program

STEP 2-> Include the necessary header files ‘iostream’ , ‘fstream’ and ‘string’

STEP 3->Implement the main() function

- declare an object ‘outputFile’ of type ‘ofstream’ to write a file

- open a file named ‘example.txt’ for writing

- check if the file is successfully opened.ifnot,print error message and return.

- use loop to read each line from file using ‘getline()’ until the end of the file is reached.

- close the file

- return 0 to indicate successful execution

STEP 4->Stop the program.

PROGRAM:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
ofstream outputFile("example.txt");

if (outputFile.is_open()) {
outputFile << "Hello, world!" << endl;
outputFile << "This is a C++ program." << endl;
outputFile.close();
cout << "Data has been written to the file." << endl;
} else {
cout << "Error: Unable to open the file for writing." << endl;
}

ifstream inputFile("example.txt");
string line;

if (inputFile.is_open()) {
cout << "Contents of the file:" << endl;
while (getline(inputFile, line)) {
cout << line << endl;
}
inputFile.close();
} else {
cout << "Error: Unable to open the file for reading." << endl;
}

return 0;
}

OUTPUT:
Data has been written to the file.
Contents of the file:
Hello, world!
This is a C++ program.
_______________________________________________________________________________________________________
5)AIM:Create a C++ program to divide values by using exception handling.

ALGORITHM:
STEP 1->Start the program

STEP 2->Include the necessary header file ‘iostream’.

STEP 3->Implement a divide() function and input numerator and denominator


- check if the denominator is zero, if it is then throw an error statement

STEP 4->Implement the main() function.

- prompt the user to input the numerator and denominator.

- divide the numerator and denominator using the exceptional handling concept

STEP 5->Stop the program.

PROGRAM:
#include <iostream>
using namespace std;

void divide(int numerator, int denominator) {


if (denominator == 0) {
throw "Division by zero error";
}
cout << "Result of division: " << numerator / denominator << endl;
}

int main() {
int numerator, denominator;

cout << "Enter numerator: ";


cin >> numerator;
cout << "Enter denominator: ";
cin >> denominator;

try {
divide(numerator, denominator);
} catch (const char* message)
{
cout << "Error: " << message << endl;
}

return 0;
}

OUTPUT:
Enter numerator: 45
Enter denominator: 5
Result of division: 9
_______________________________________________________________________________________________________

6) AIM:Create a C++ program by demonstrating the virtual function


ALGORITHM:
STEP 1->Start the program

STEP 2->Include the necessary header file ‘iostream’

STEP 3->Define a class ‘base’ with two member functions:

- ‘show()’ : prints “base class show”

- ‘display()’ : declared as a virtual function

STEP 4-> Define a class ‘drive’ inherited publicly from ‘base’ with two member functions

- ‘display()’ : prints “drive class display”

- ‘show()’ : prints “drive class show”

STEP 5-> Implement the main() function:

- create object ‘obj1’ and ‘obj2’ of classes ‘base’ and ‘derived’ respectively.

- declare a pointer ‘bptr’ of type ‘base’

- point ‘bptr’ to the object ‘obj1’ and call ‘display()’ and ‘show()’ through ‘bptr’

- point ’bptr’ to the object ‘obj2’ and call ‘display()’ and ‘show()’ through ‘bptr’

STEP 6-> Stop the program

PROGRAM:
#include <iostream>
using namespace std;

class base {
public:
void show() {
cout << "\n Base class show:";
}

virtual void display() {


cout << "\n Base class display:";
}
};

class drive : public base {


public:

void display() {
cout << "\n Drive class display:";
}
void show() {
cout << "\n Drive class show:";
}
};

int main() {
base obj1;
base *p;
cout << "\n\t P points to base:\n";

p = &obj1;
p->display();
p->show();

cout << "\n\n\t P points to drive:\n";


drive obj2;
p = &obj2;
p->display();
p->show();
}

OUTPUT:
P points to base:

Base class display:


Base class show:

P points to drive:

Drive class display:


Base class show:

_______________________________________________________________________________________________________
7)AIM:Create a C++ program to make a stack and complete the following given below:
(1)Push “3” values (2)Pop “1” value (3)Display the stack
ALGORITHM:
STEP 1->Start the program

STEP 2->Include the necessary header files 'iostream'

STEP 3->declare global variables 'stack[5]' ,'n=5' and 'top=-1'

STEP 4->Implement a display() function:

-check if the stack element is empty, if not then print the stack elements

-if is empty then print " the stack is empty"

STEP 5->Implement the main() function

-declare the variables 'ch' and 'val'


-print all the operations that can be done using stack

-using the loop ,prompt the user to input the choice

-implement the switch case statement to operate according to the choice made by the

user.

STEP 6->Stop the program.

PROGRAM:
#include <iostream>
using namespace std;
int stack[5], n=5, top=-1;
void display() {
if(top>=0) {
cout<<"Stack elements are:";
for(int i=top; i>=0; i--)
cout<<stack[i]<<" ";
cout<<endl;
} else
cout<<"Stack is empty";
}
int main() {
int ch, val;
cout<<"1) Push in stack"<<endl;
cout<<"2) Pop from stack"<<endl;
cout<<"3) Display stack"<<endl;
cout<<"4) Exit"<<endl;
do {
cout<<"Enter choice: "<<endl;
cin>>ch;
switch(ch) {
case 1: {
cout<<"Enter value to be pushed:"<<endl;
cin>>val;
if(top>=n-1)
cout<<"Stack Overflow"<<endl;
else {
top++;
stack[top]=val;
}
break;
}
case 2: {

if(top<=-1)
cout<<"Stack Underflow"<<endl;
else
cout<<"The popped element is "<< stack[top] <<endl;
top--;
break;
}
case 3: {
display();

break;
}
case 4: {
cout<<"Exit"<<endl;
break;
}
default: {
cout<<"Invalid Choice"<<endl;
}
}
}while(ch!=4);
return 0;
}

OUTPUT:
1) Push in stack
2) Pop from stack
3) Display stack
4) Exit
Enter choice:
1
Enter value to be pushed:
12
Enter choice:
1
Enter value to be pushed:
14
Enter choice:
1
Enter value to be pushed:
16
Enter choice:
2
The popped element is 16
Enter choice:
3
Stack elements are:14 12
Enter choice:
4
Exit
_______________________________________________________________________________________________________
8)AIM:Create a C++ program to make a queue and satisfy the following given below:
(1)Enqueue “4” values (2)Dequeue “2” values (3)Display the queue

ALGORITHM:
STEP 1->Start the program

STEP 2->Include the necessary header files 'iostream' and 'queue'

STEP 3->Implement a display() function

-check if the queue is empty ,if it is then print "Queue is empty".

STEP 4->Implement the main() function

-print all the operations that can be done by queues

-declare the variables 'choice ' and 'value'

-using the loop prompt the user to input the choice

-Implement the switch case statement to operate according to the choice made by the

user.
STEP 5->Stop the program.

PROGRAM:
#include <iostream>
#include <queue>
using namespace std;
void display(queue<int>& q) {
if (!q.empty()) {
cout << "Queue elements: ";
queue<int> tempQueue = q;
while (!tempQueue.empty()) {
cout << tempQueue.front() << " ";
tempQueue.pop();
}
cout << endl;
} else {
cout << "Queue is empty." << endl;
}
}
int main() {
cout << "\nQueue Operations:" << endl;
cout << "1. Enqueue" << endl;
cout << "2. Dequeue" << endl;
cout << "3. Display queue"<<endl;
cout << "4. Exit" << endl;
queue<int> myQueue;
int choice, value;
do {
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 1:
cout << "Enter value to enqueue: ";
cin >> value;
myQueue.push(value);
cout << "Value " << value << " enqueued successfully." << endl;
break;
case 2:
if (!myQueue.empty()) {
cout << "Dequeued value: " << myQueue.front() << endl;
myQueue.pop();
} else {
cout << "Queue is empty. No elements to dequeue." << endl;
}
break;
case 3:
display(myQueue);
case 4:
cout << "QUEUE EXITED." << endl;
break;
default:
cout << "Invalid choice. Please enter a valid option." << endl;
}
} while (choice != 4);

return 0;
}

OUTPUT:
Queue Operations:
1. Enqueue
2. Dequeue
3. Display queue
4. Exit
Enter your choice: 1
Enter value to enqueue: 22
Value 22 enqueued successfully.
Enter your choice: 1
Enter value to enqueue: 24
Value 24 enqueued successfully.
Enter your choice: 1
Enter value to enqueue: 26
Value 26 enqueued successfully.
Enter your choice: 1
Enter value to enqueue: 28
Value 28 enqueued successfully.
Enter your choice: 2
Dequeued value: 22
Enter your choice: 2
Dequeued value: 24
Enter your choice: 3
Queue elements: 26 28
Exiting program.
Enter your choice: 4
QUEUE EXITED.

_______________________________________________________________________________________________________
9)AIM:Create a C++ program to sort the values using Bubble Sort & get values from the user.

ALGORITHM:
STEP 1->Start the program

STEP 2->Include the necessary header files ‘iostream’

STEP 3->Implement a ‘bubbleSort(int arr[],int n)’ function to sort the array elements

-within the outer loop, start another loop to iterate from the first element to the

element before the last unsorted element.

-compare each element with its adjacent element

STEP 4->Implement the main() function

-declare the variable ‘n’

-prompt the user to input the number of elements

-declare another variable ‘arr[n]’ and prompt the user to enter the elements

-call the ‘bubbleSort(arr,n)’ function to sort the elements of the array

-print the sorted array

STEP 5->Stop the program.

PROGRAM:
#include <iostream>
using namespace std;

void bubbleSort(int arr[], int n) {


for (int i = 0; i < n - 1; ++i) {
for (int j = 0; j < n - i - 1; ++j) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;

int arr[n];
cout << "Enter " << n << " elements:" << endl;
for (int i = 0; i < n; ++i) {
cin >> arr[i];
}

bubbleSort(arr, n);

cout << "Sorted array:" << endl;


for (int i = 0; i < n; ++i) {
cout << arr[i] << " ";
}
cout << endl;

return 0;
}

OUTPUT:

Enter the number of elements: 5


Enter 5 elements:
67
45
88
1
36
Sorted array:
1 36 45 67 8

_______________________________________________________________________________________________________

10)AIM:Create a C++ program to find the position of the value by implementing binary searching & get
Values from the user.
ALGORITHM:
STEP 1->Start the program

STEP 2->Include the header file ‘iostream’

STEP 3->Implement ‘binarySearch(int arr[ ], int n, int largest)’ function to implement the binary

searching.

-declare the variables ‘left’ and ‘right’

-using the loop concept, arrange the array elements

STEP 4->Implement the main() function

-declare the variables ‘n’ and ‘target’

-prompt the user to input the number of elements in the array

-declare another variable ‘arr[n]’

-then prompt the user to enter the target element to search

-check if targeted element is found in the array, if not then print “not found in the array”

STEP 5->Stop the program.

PROGRAM:
#include <iostream>
using namespace std;
binarySearch(int arr[], int n, int target) {
int left = 0;
int right = n - 1;

while (left <= right) {


int mid = left + (right - left) / 2;
if (arr[ mid] == target) {
return mid;
}

if (arr[mid] < target) {


left = mid + 1;
}
else {
right = mid - 1;
}
}

return -1;
}
int main() {
int n, target;
cout << "Enter the number of elements in the array: ";
cin >> n;

int arr[n];
cout << "Enter " << n << " sorted integers:" << endl;
for (int i = 0; i < n; ++i) {
cin >> arr[i];
}

cout << "Enter the target element to search: ";


cin >> target;

int index = binarySearch(arr, n, target);

if (index != -1) {
cout << "Element " << target << " found at index " << index << endl;
} else {
cout << "Element " << target << " not found in the array." << endl;
}

return 0;
}

OUTPUT:
Enter the number of elements in the array: 5
Enter 5 sorted integers:
22 44 66 88 99
Enter the target element to search: 88
Element 88 found at index 3
_______________________________________________________________________________________________________

11)AIM:Create a C++ program to make an inorder traversal program for(11,33,55,77,99)values.

ALGORITHM:
STEP 1->Start the program

STEP 2->Include the necessary header file ‘iostream’

STEP 3->Define a structure `node` to represent a node in a binary tree. Each node contains an

integer data value and pointers to its left and right child nodes.

STEP 4->Implement a function `createnode` to create a new node with the given data:

-Allocate memory for a new node using `new`.


-Check if memory allocation was successful. If not, print an error message and return

`NULL`.

-Set the data of the new node.

-Set both left and right child pointers to `NULL`.

-Return the pointer to the new node.

STEP 5-> Implement a recursive function `inorder` to perform an inorder traversal of the binary

tree:

-If the current node is `NULL`, return.

-Print the data of the current node.

-Recursively traverse the left subtree.

-Recursively traverse the right subtree.

STEP 6-> Implement the `main` function:

-Create a binary tree with some nodes and set their values.

-Print a message indicating the inorder traversal is being performed.

-Call the `inorder` function with the root node to perform inorder traversal.

-Return 0 to indicate successful completion.

STEP 7->Stop the program

PROGRAM:
#include <iostream>
using namespace std;
struct node {
int data;
node* left;
node* right;
};
node *createnode(int data)
{
node *newnode =new node();
if(!newnode)
{
cout<<"memory error \n";
return NULL;
}
newnode->data=data;
newnode->left=newnode->right =NULL;
return newnode;
}
void inorder(node* temp) {
if (temp == NULL)
return;

inorder(temp->left);
cout << temp->data << " ";
inorder(temp->right);
}

int main() {
node* root = createnode(11);
root->left = createnode(33);
root->right = createnode(55);
root->left->left = createnode(77);
root->left->right = createnode(99);

cout << "Inorder Traversal: ";


inorder(root);

return 0;
}

OUTPUT:
Inorder Traversal: 77 33 99 11 55
_______________________________________________________________________________________________________

12)AIM:Create a C++ program to make a Singly Linked List using Malloc function.

ALGORITHM:
STEP 1->Start the program.

STEP 2->Include the necessary header file `iostream`.

STEP 3->Define a struct `node` to represent a node in a linked list. Each node contains an

integer data value and a pointer to the next node.

STEP 4->Declare a global pointer `head` initialised to `NULL` to point to the first node of the

linked list.

STEP 5->Implement the `append` function to insert a new node with given data at the

beginning of the linked list:

-Allocate memory for a new node using `malloc`.

-Set the data of the new node to the given data.

-Set the `next` pointer of the new node to point to the current `head`.
-Update the `head` pointer to point to the new cell.

STEP 6->Implement the `show` function to display the elements of the linked list:

-Initialise a pointer `ptr` to traverse the linked list, starting from the `head`.

-While `ptr` is not `NULL`, print the data value of the current node and move `ptr` to

the next node.

STEP 7->Implement the `main` function:

-Insert several elements into the linked list using the `insert` function.

-Print a message indicating that the linked list is being displayed.

-Call the `show function to print the elements of the linked list.

-Return 0 to indicate successful completion of the program.

STEP 8->Stop the program.

PROGRAM:
#include<iostream>
#include<cstdlib>
using namespace std;
struct node
{
int data;
struct node *next;
};
struct node* head =NULL;
void append(int value)
{
struct node* new_cell =(struct node*)
malloc (sizeof(struct node));
new_cell->data = value;
new_cell->next = head;
head = new_cell;
}
void show()
{
struct node* ptr;
ptr = head;
while(ptr != NULL)
{
cout<<ptr->data<<" --> ";
ptr=ptr->next;

}
}
int main()
{
append(11);
append(22);
append(33);
append(44);
cout<<"THE CREATED SINGLY LINKED LIST IS : \n";
show();
return 0;
}

OUTPUT:
THE CREATED SINGLY LINKED LIST IS :
44 --> 33 --> 22 --> 11 -->

*****************************************************************************************************

You might also like