0% found this document useful (0 votes)
7 views123 pages

Dsa Tasks

Some important codes and questions that might come in your final paper.

Uploaded by

5124rabia
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)
7 views123 pages

Dsa Tasks

Some important codes and questions that might come in your final paper.

Uploaded by

5124rabia
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/ 123

LAB 6

Name: Areeba Anjum


Roll no: 2330-0098
Department: BS(SE)
Course: Data Structures and Algorithms
Submitted to: Sir Bilal Khan
Dated: November 08, 2024
Task 1: Implement the following functions for linked list:
1) Insert front
2) Insert End
3) Insert after number
4) Delete front
5) Delete End
6) Delete any number from list
7) Display all element
8) Limit user so that he/she can only add 10 numbers in the list. After
that give error that list is full.
Code:
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
class LinkedList
{
private:
Node* head;
int count;
public:
LinkedList()
{
head=NULL;
count=0;
}
void insertFront(int value)
{
if (count >= 10)
{
cout << "List is full. Cannot add more elements." << endl;
}
Node* newNode = new Node{value, head};
head = newNode;
count++;
}
void insertEnd(int value)
{
if (count >= 10)
{
cout << "List is full. Cannot add more elements." << endl;
}
Node* newNode = new Node{value,NULL};
if (head==NULL)
{
head = newNode;
} else
{
Node* temp = head;
while (temp->next)
{
temp = temp->next;
}
temp->next = newNode;
}
count++;
}
void insertAfter(int afterValue, int value)
{
if (count >= 10)
{
cout << "List is full. Cannot add more elements." << endl;
}
Node* temp = head;
while (temp)
{
if (temp->data == afterValue)
{
Node* newNode = new Node{value, temp->next};
temp->next = newNode;
count++;
return;
}
temp = temp->next;
}
cout << "Number not found"<< endl;
}
void deleteFront()
{
if (head==NULL)
{
cout << "List is empty." << endl;
return;
}
Node* temp = head;
head = head->next;
delete temp;
count--;
}
void deleteEnd()
{
if (head==NULL)
{
cout << "List is empty." << endl;
return;
}
if (!head->next)
{
delete head;
head = NULL;
} else
{
Node* temp = head;
while (temp->next->next)
{
temp = temp->next;
}
delete temp->next;
temp->next = NULL;
}
count--;
}
void deleteNumber(int value)
{
if (head==NULL) {
cout << "List is empty." << endl;
return;
}
if (head->data == value)
{ // If the head needs to be deleted
deleteFront();
return;
}
Node* temp = head;
while (temp->next)
{
if (temp->next->data == value)
{
Node* toDelete = temp->next;
temp->next = temp->next->next;
delete toDelete;
count--;
return;
}
temp = temp->next;
}
cout << " Number not found" << endl;
}
void display()
{
if (head==NULL)
{
cout << "The list is empty." << endl;
return;
}
Node* temp = head;
cout << "Elements in the list: ";
while (temp!=NULL)
{
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
};
int main()
{
LinkedList list;
int choice, value, afterValue;
while (true)
{
cout << "1. Insert Front\n";
cout << "2. Insert End\n";
cout << "3. Insert After Number\n";
cout << "4. Delete Front\n";
cout << "5. Delete End\n";
cout << "6. Delete Any Number\n";
cout << "7. Display All Elements\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice)
{
case 1:
cout << "Enter value to insert at front: ";
cin >> value;
list.insertFront(value);
break;

case 2:
cout << "Enter value to insert at end: ";
cin >> value;
list.insertEnd(value);
break;

case 3:
cout << "Enter value to insert after: ";
cin >> afterValue;
cout << "Enter value to insert: ";
cin >> value;
list.insertAfter(afterValue, value);
break;

case 4:
list.deleteFront();
break;

case 5:
list.deleteEnd();
break;

case 6:
cout << "Enter value to delete: ";
cin >> value;
list.deleteNumber(value);
break;

case 7:
list.display();
break;
}
}
}
Output:
Task 2: Use Practice task 1 and add two functions Remove_Duplicate() and
Count() in the class. Remove_Duplicate() function should remove all the
number that are occurring more than one time. Count() function should count
the number of nodes present at any time in the list.
Code;
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
class LinkedList
{
private:
Node* head;
int count;
public:
LinkedList()
{
head=NULL;
count=0;
}
void insertFront(int value)
{
if (count >= 10)
{
cout << "List is full. Cannot add more elements." << endl;
}
Node* newNode = new Node{value, head};
head = newNode;
count++;
}
void insertEnd(int value)
{
if (count >= 10)
{
cout << "List is full. Cannot add more elements." << endl;
}
Node* newNode = new Node{value,NULL};
if (head==NULL)
{
head = newNode;
} else
{
Node* temp = head;
while (temp->next)
{
temp = temp->next;
}
temp->next = newNode;
}
count++;
}
void insertAfter(int afterValue, int value)
{
if (count >= 10)
{
cout << "List is full. Cannot add more elements." << endl;
}
Node* temp = head;
while (temp)
{
if (temp->data == afterValue)
{
Node* newNode = new Node{value, temp->next};
temp->next = newNode;
count++;
return;
}
temp = temp->next;
}
cout << "Number not found"<< endl;
}
void Remove_Duplicate()
{
Node* current = head;
while (current)
{
Node* runner = current;
while (runner->next)
{
if (runner->next->data == current->data)
{
Node* temp = runner->next;
runner->next = runner->next->next; // Skip the duplicate
delete temp;
count--;
} else
{
runner = runner->next;
}
}
current = current->next;
}
}
int Count()
{
return count;
}
void deleteFront()
{
if (head==NULL)
{
cout << "List is empty." << endl;
return;
}
Node* temp = head;
head = head->next;
delete temp;
count--;
}
void deleteEnd()
{
if (head==NULL)
{
cout << "List is empty." << endl;
return;
}
if (!head->next)
{
delete head;
head = NULL;
} else
{
Node* temp = head;
while (temp->next->next)
{
temp = temp->next;
}
delete temp->next;
temp->next = NULL;
}
count--;
}
void deleteNumber(int value)
{
if (head==NULL) {
cout << "List is empty." << endl;
return;
}
if (head->data == value)
{ // If the head needs to be deleted
deleteFront();
return;
}
Node* temp = head;
while (temp->next)
{
if (temp->next->data == value)
{
Node* toDelete = temp->next;
temp->next = temp->next->next;
delete toDelete;
count--;
return;
}
temp = temp->next;
}
cout << " Number not found" << endl;
}
void display()
{
if (head==NULL)
{
cout << "The list is empty." << endl;
return;
}
Node* temp = head;
cout << "Elements in the list: ";
while (temp!=NULL)
{
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
};
int main()
{
LinkedList list;
int choice, value, afterValue;
while (true)
{
cout << "1. Insert Front\n";
cout << "2. Insert End\n";
cout << "3. Insert After Number\n";
cout << "4. Delete Front\n";
cout << "5. Delete End\n";
cout << "6. Delete Any Number\n";
cout << "7. Display All Elements\n";
cout << "8. Remove Duplicates\n";
cout << "9. Count Nodes\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice)
{
case 1:
cout << "Enter value to insert at front: ";
cin >> value;
list.insertFront(value);
break;

case 2:
cout << "Enter value to insert at end: ";
cin >> value;
list.insertEnd(value);
break;

case 3:
cout << "Enter value to insert after: ";
cin >> afterValue;
cout << "Enter value to insert: ";
cin >> value;
list.insertAfter(afterValue, value);
break;

case 4:
list.deleteFront();
break;

case 5:
list.deleteEnd();
break;

case 6:
cout << "Enter value to delete: ";
cin >> value;
list.deleteNumber(value);
break;

case 7:
list.display();
break;

case 8:
list.Remove_Duplicate();
cout << "Duplicates removed." << endl;
break;
case 9:
cout << "Number of nodes in the list: " << list.Count() << endl;
break;
}
}
}
Output:
Task 3: Manage data of Books (Title, Authors, Edition, Price) using linked list.
Add Books in the list. Now delete all Books having price more than 2000 from
the list.
Code:
#include <iostream>
#include <string>
using namespace std;
struct Book
{
string title;
string authors;
string edition;
double price;
Book* next;
};
class BookList
{
private:
Book* head;
public:
BookList()
{
head==NULL;
}
void addBook(const string& title, const string& authors, const string& edition,
double price)
{
Book* newBook = new Book{title, authors, edition, price, head};
head = newBook;
}
void deleteExpensiveBooks()
{
Book* current = head;
Book* previous =NULL;
while (current)
{
if (current->price > 2000)
{
if (previous)
{
previous->next = current->next;
} else
{
head = current->next; // Update head if the first node is deleted
}
Book* toDelete = current;
current = current->next;
delete toDelete;
} else {
previous = current;
current = current->next;
}
}
}
void displayBooks()
{
if (head==NULL)
{
cout << "No books in the list." << endl;
}
Book* temp = head;
cout << "Books in the list:\n";
while (temp!=NULL)
{
cout << "Title: " << temp->title
<< ", Authors: " << temp->authors
<< ", Edition: " << temp->edition
<< ", Price: " << temp->price << endl;
temp = temp->next;
}
}
};
int main()
{
BookList bookList;
int choice;
string title, authors, edition;
double price;
while (true)
{
cout << "1. Add Book\n";
cout << "2. Delete Expensive Books (Price > 2000)\n";
cout << "3. Display All Books\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice)
{
case 1:
cin.ignore();
cout << "Enter title: ";
getline(cin, title);
cout << "Enter authors: ";
getline(cin, authors);
cout << "Enter edition: ";
getline(cin, edition);
cout << "Enter price: ";
cin >> price;
bookList.addBook(title, authors, edition, price);
break;

case 2:
bookList.deleteExpensiveBooks();
cout << "All books with price greater than 2000 have been deleted." <<
endl;
break;

case 3:
bookList.displayBooks();
break;
}
}
}
Output:
Lab No. 07

Course Name: Applied Physics


Submitted by: Rabia Sarfraz
Roll No.: 2330-0070
Class Section: FA23/BS(SE)
Submitted to: Sir Ishaq
DATE: 24th October, 2024

“On my honor, as a Sir Syed CASE Institute Islamabad student, I have neither
given nor received unauthorized assistance on this academic work.
Task No. 01: Write a program to implement a stack using linked list. Stack
is of Books (Title, Author, Price). Your program should find or delete a book
entered by user from the stack. Remember that to reach a book in stack all
the books above must be checked first.
Code:
#include<iostream>
#include<string>
#include<cstddef>
using namespace std;
struct node{
string title;
string author;
double price;
node* next;
};
class stack{
private:
node* head;
public:
stack();
void push(string name, string author, double cost);
void pop();
void display();
};
stack::stack()
{
head=NULL;
}
void stack::push(string name, string author, double cost)
{
node* newnode= new node;
newnode->title=name;
newnode->author=author;
newnode->price=cost;
newnode->next=head;
head=newnode;
}
void stack::pop()
{
if(head==NULL)
{
cout<<"Stack is empty. Cannot pop!"<<endl;
return;
}
else
{
node* temp=head;
head= head->next;
delete temp;
}
}
void stack::display()
{
if(head==NULL)
{
cout<<"stack is empty. Cannot display anything!"<<endl;
return;
}
else
{
node* temp=head;
while(temp!=NULL)
{
cout<<"Book Title: "<<temp->title<<endl;
cout<<"Author: "<<temp->author<<endl;
cout<<"Price: "<<temp->price<<endl;
temp=temp->next;
}
}
}
int main()
{
stack s; //object
int choice;
cout<<"Menue: "<<endl;
cout<<"1. Enter book details in the stack."<<endl<<"2. Display book
details."<<endl;
cout<<"3. Delete book details."<<endl<<"4. Exit the program."<<endl;
for(int i=0;;i++)
{
cout<<"Enter your choice: ";
cin>>choice;
if(choice==1)
{
node book;
cout<<"Enter the Title of the book: ";
cin.ignore();
getline(cin,book.title);
cout<<"Enter the Author: ";
cin.ignore();
getline(cin,book.author);
cout<<"Enter the Price: ";
cin>>book.price;
s.push(book.title,book.author, book.price);
}
if(choice==2)
{
cout<<"Details of all books are: "<<endl;
s.display();
}
if(choice==3)
{
s.pop();
cout<<"Deleted details."<<endl;
}
if(choice==4)
{
cout<<"program exited successfully."<<endl;
break;
}
}
return 0;
}
Result:

Task No. 02: Organization ABC is taking online orders from its customers.
Save the following information for each order:

 OrderID (Auto incremented)


 Customer name
 Address
 Number of items in the order
 Payment of order

Orders will be processed on first come first server basis.


Code:
#include<iostream>
#include<string>
#include<cstddef>
using namespace std;
struct node{
int id;
string name;
string address;
int itemsNo;
double price;
node* next;
};
class queue{
private:
node* head;
public:
queue(); //constructor
void enqueue(string name, string address, int itemsNo, double cost);
void dequeue();
void display();
};
queue::queue()
{
head=NULL;
}
void queue::enqueue(string name, string address, int itemsNo, double cost)
{
node* newnode= new node;
newnode->name=name;
newnode->address=address;
newnode->itemsNo=itemsNo;
newnode->price=cost;
newnode->next=head;
head=newnode;
}
void queue::dequeue()
{
if(head==NULL)
{
cout<<"Queue is empty. Cannot dequeue!"<<endl;
return;
}
else
{
node* temp=head;
head= head->next;
delete temp;
}
}
void queue::display()
{
if(head==NULL)
{
cout<<"queue is empty. Cannot display anything!"<<endl;
return;
}
else
{
node* temp=head;
int count=1;
while(temp!=NULL)
{
cout<<"Custumer Id: "<<count<<endl;
cout<<"Customer Name: "<<temp->name<<endl;
cout<<"Address: "<<temp->address<<endl;
cout<<"Number of items: "<<temp->itemsNo<<endl;
cout<<"Total price: "<<temp->price<<endl;
temp=temp->next;
count++;
}
}
}
int main()
{
queue q; //object
int choice;
cout<<"Menue: "<<endl;
cout<<"1. Enter details of the customers."<<endl<<"2. Display all the oredrs
placed"<<endl;
cout<<"3. Delete the order details."<<endl<<"4. Exit the program."<<endl;
for(int i=0;;i++)
{
cout<<"Enter your choice: ";
cin>>choice;
if(choice==1)
{
node order;
cout<<"Enter Customer's Name: ";
cin.ignore();
getline(cin,order.name);
cout<<"Enter the Address: ";
cin.ignore();
getline(cin,order.address);
cout<<"Enter the Number of Items: ";
cin>>order.itemsNo;
cout<<"Enter the Total Price: ";
cin>>order.price;
q.enqueue( order.name ,order.address,order.itemsNo, order.price);
}
if(choice==2)
{
cout<<"Details of orders are: "<<endl;
q.display();
}
if(choice==3)
{
q.dequeue();
}
if(choice==4)
{
cout<<"Program Exited successfully."<<endl;
break;
}
}
return 0;
}
Result:
The End!
Lab No. 08

Course Name: Data Structures and Algorithms


Submitted by: Rabia Sarfraz
Roll No.: 2330-0070
Class Section: FA23/BS(SE)
Submitted to: Sir Bilal Khan
DATE: 18th December, 2024

“On my honor, as a Sir Syed CASE Institute Islamabad student, I have neither
given nor received unauthorized assistance on this academic work.
Question:
Implement a program using Doubly LinkedList. Your doubly linked
list should store information of students (Reg_no., Name, CGPA,
city, age). Your program should provide following functionalities:

 Insert at Front
 Insert at Rear
 Insert in middle
 Delete from front
 Delete from rear
 Delete from middle
 Display all the data

Code:
#include<iostream>
#include<string>
using namespace std;
struct node{
string name;
int regNo;
float cgpa;
string city;
int age;
node* next;
node* prev;
};
class DElinkList{
private:
node* front;
node* rear;
public:
DElinkList();
void insertAtFront(int regNo, string name, float cgpa, string
city, int age);
void insertAtRear(int regNo, string name, float cgpa, string
city, int age);
void insertAtIndex(int index, int regNo, string name, float
cgpa, string city,int age);
void deleteAtFront();
void deleteAtRear();
void deleteAtIndex(int index);
void display();
};
DElinkList::DElinkList()
{
front=NULL;
rear=NULL;
}
void DElinkList::insertAtFront(int regNo, string name, float cgpa, string
city, int age)
{
node* newnode= new node;
newnode->regNo=regNo;
newnode->name=name;
newnode->cgpa=cgpa;
newnode->city=city;
newnode->age=age;
newnode->next=NULL;
newnode->prev=NULL;
if(front==NULL)
{
front=rear=newnode;
}
else
{
newnode->next=front;
front->prev=newnode;
front=newnode;
}
}
void DElinkList::insertAtRear(int regNo, string name, float cgpa, string
city, int age)
{
node* newnode= new node;
newnode->regNo=regNo;
newnode->name=name;
newnode->cgpa=cgpa;
newnode->city=city;
newnode->age=age;
newnode->next=NULL;
newnode->prev=NULL;
if(!(front==NULL))
{
rear->next=newnode;
newnode->prev=rear;
rear=newnode;
}
else
{
front=rear=newnode;
}
}
void DElinkList::insertAtIndex(int index, int regNo, string name, float
cgpa, string city, int age)
{
if (index==0)
{
insertAtFront(regNo, name, cgpa, city, age);
return;
}
node* newnode=new node;
newnode->regNo=regNo;
newnode->name=name;
newnode->cgpa=cgpa;
newnode->city=city;
newnode->age=age;
node* temp=front;
for (int i=0;i<index-1&&temp!=NULL;i++)
{
temp=temp->next;
}
if (temp==NULL||temp->next==NULL)
{
insertAtRear(regNo, name, cgpa, city, age);
}
else
{
newnode->next=temp->next;
newnode->prev=temp;
if (temp->next!=NULL)
{
temp->next->prev=newnode;
}
temp->next=newnode;
}
}
void DElinkList::deleteAtFront()
{
if(front==NULL)
{
cout<<"List is empty"<<endl;
}
else
{
node* temp=front;
front=front->next;
front->prev=NULL;
delete temp;
}
}
void DElinkList::deleteAtRear()
{
if(front==NULL)
{
cout<<"Empty."<<endl;
}
else
{
node* temp=rear;
rear=rear->prev;
rear->next=NULL;
delete temp;
}
}
void DElinkList::deleteAtIndex(int index)
{
if (index==0)
{
deleteAtFront();
return;
}
node* temp=front;
for (int i=0;i<index&&temp!=NULL;i++)
{
temp=temp->next;
}
if (temp==NULL)
{
cout<<"Invalid index"<<endl;
} else if (temp->next==NULL)
{
deleteAtRear();
} else
{
temp->prev->next=temp->next;
temp->next->prev=temp->prev;
delete temp;
}
}
void DElinkList::display()
{
node *temp=front;
while(temp!=NULL)
{
cout<<"Registration Number: "<<temp-
>regNo<<endl<<"Name: "<<temp->name<<endl;
cout<<"Cgpa: "<<temp->cgpa<<endl<<"City:
"<<temp->city<<endl<<"Age: "<<temp->age<<endl;
temp=temp->next;
}
cout<<endl;
}
int main()
{
DElinkList dll;
cout<<"List when inserted at front: "<<endl;
dll.insertAtFront(1,"Zara",3.5,"Rawalpindi",20);
dll.insertAtFront(2,"Saima",3.67,"Tarnol",19);
dll.display();
cout<<"List when iserted at the rear: "<<endl;
dll.insertAtRear(3,"Zade",3.8,"Islamabad",23);
dll.insertAtRear(4,"Addie",3.03,"Islamabad",20);
dll.insertAtRear(7,"Sibbel",3.33,"Islamabad",19);
dll.display();
cout<<"List when inserted at the index: "<<endl;
dll.insertAtIndex(1,5,"Sara",3.6,"Rawalpindi",21);
dll.insertAtIndex(4,6,"Alex",3.78,"California",23);
dll.display();
cout<<"List after deleting from the front: "<<endl;
dll.deleteAtFront();
dll.display();
cout<<"List after deleting from the rear: "<<endl;
dll.deleteAtRear();
dll.display();
cout<<"List after deleting from the certain index: "<<endl;
dll.deleteAtIndex(4);
dll.display();
return 0;
}
Result:
THE END!
Lab No. 09

Course Name: Data Structures and Algorithms


Submitted by: Rabia Sarfraz
Roll No.: 2330-0070
Class Section: FA23/BS(SE)
Submitted to: Sir Bilal
DATE: 1st January, 2025
Task No. 01:
Write a C++ program that creates a static array of size 10 and then passes this array
to a function that prints the array elements using recursion.
Code:
#include<iostream>
using namespace std;
void printArray(int arr[], int size, int index)
{
if(index==size)
{
return;
}
else
{
cout<<arr[index]<<" ";
printArray(arr, size, index+1);
}
}
int main()
{
int arr[10]={1,2,3,4,5,6,7,8,9,10};
cout<<"Array elements are: "<<endl;
printArray(arr, 10, 0);
cout<<endl;
return 0;
}
Result:

Task No. 02:


Write a C++ program to check whether the number is a prime.
Code:
#include<iostream>
using namespace std;
bool isPrime(int n, int divisor=2)
{
if(n<=1)
{
return false;
}
if(divisor*divisor>n)
{
return true;
}
if(n%2==0)
{
return false;
}
isPrime(n, divisor+1);
}
int main()
{
int n;
cout<<"Enter the number you want to check is prime or not: ";
cin>>n;
if(isPrime(n))
{
cout<<"It's a prime number."<<endl;
}
else
{
cout<<"It's not a prime number."<<endl;
}
return 0;
}
Result:

Task No. 03:


Create a C++ program that takes two integers from the user. Your program
should also have a recursive function that will display odd numbers between
the ranges given by the user.
Code:
#include<iostream>
using namespace std;
void displayOddNumbers(int start, int end)
{
if(start==end)
{
return;
}
else
{
if(start%2!=0)
{
cout<<start<<" ";
}
displayOddNumbers(start+1, end);
}
}
int main()
{
int n,m;
cout<<"Enter the starting number from where you want to print
odd numbers: ";
cin>>n;
cout<<"Enter the number where you want to end printing odd
numbers: ";
cin>>m;
displayOddNumbers(n,m);
return 0;
}
Result:
Task No. 04:
Write a program to create a static character array. Write a recursive function
Find Palindrome which should tell whether or not the entered set of
characters is the palindromic sequence.
Code:
#include <iostream>
#include<cstring>
using namespace std;
bool isPalindrome(char arr[], int start, int end)
{
if (start>=end)
{
return true;
}
if (arr[start]!=arr[end])
{
return false;
}
return isPalindrome(arr,start + 1,end - 1);
}

int main()
{
char arr[100];
cout<<"Enter a Char Array: ";
cin>>arr;
int length=strlen(arr);
if (isPalindrome(arr,0,length-1))
{
cout<<arr<<" is a palindrome."<<endl;
}
else
{
cout<<arr<<" is not a palindrome."<<endl;
}
return 0;
}
Result:

The end!
Recursion Tasks
1. Reverse array
#include <iostream>
using namespace std;
void reverseArray(int arr[], int start, int end)
{
if (start >= end)
{
return;
}
else
{
swap(arr[start], arr[end]); // swapping the first and last and up to so on
reverseArray(arr,start + 1,end - 1); //recursive call
}
}

int main()
{
int n;
cout<<"Enter the size: ";
cin>>n;
int arr[n];
cout<<"Enter "<<n<<" elements in an array: "<<endl;
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
reverseArray(arr, 0, n - 1);
cout << "Reversed Array: ";
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
cout << endl;
return 0;
}

2. Prime Number Check


#include <iostream>
using namespace std;
bool isPrime(int n, int divisor = 2)
{
if (n <= 1)
{
return false;
}
if (divisor * divisor > n)
{
return true;
}
if (n % divisor == 0)
{
return false;
}
return isPrime(n, divisor + 1);
}

int main()
{
int num;
cout << "Enter a number: ";
cin >> num;
if (isPrime(num))
{
cout << num << " is a prime number." << endl;
} else
{
cout << num << " is not a prime number." << endl;
}
return 0;
}
3. Odd Numbers Between Two Numbers
#include <iostream>
using namespace std;

void printOddNumbers(int start, int end)


{
if (start > end)
{
return;
}
if (start % 2 != 0)
{
cout << start << " ";
}
printOddNumbers(start + 1, end);
}

int main()
{
int start, end;
cout << "Enter two numbers: ";
cin >> start >> end;

cout << "Odd numbers in the range: ";


printOddNumbers(start, end);
cout << endl;

return 0;
}

4. Print an Array
#include <iostream>
using namespace std;
void printArray(int arr[], int size, int index = 0)
{
if (index == size)
{
return;
}
cout << arr[index] << " ";
printArray(arr, size, index + 1);
}

int main()
{
int n;
cout<<"Enter the size of an array: ";
cin>>n;
int arr[n];
cout<<"Enter "<<n<<" elements in an array: "<<endl;
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
cout << "Array elements: ";
printArray(arr, n);
cout << endl;
return 0;
}

5. String is Palindrome or not


#include <iostream>
#include <string>
using namespace std;
bool isPalindrome(string str, int start, int end)
{
if (start >= end)
{
return true;
}
if (str[start] != str[end])
{
return false;
}
return isPalindrome(str, start + 1, end - 1);
}

int main()
{
string str;
cout<<"Enter a string: ";
cin>>str;

if (isPalindrome(str, 0, str.length() - 1))


{
cout << str << " is a palindrome." << endl;
}
else
{
cout << str << " is not a palindrome." << endl;
}
return 0;
}

6. Fibonacci Series
#include<iostream>
using namespace std;
int fibonacci_series(int num)
{
if(num<=1)
{
return num;
}
else
{
return fibonacci_series(num-1)+fibonacci_series(num-2);
}
}
int main()
{
int num;
cout<<"Enter the positive integer: ";
cin>>num;
if(num<=0)
{
cout<<"Please enter again: ";
cin>>num;
}
else
{
cout<<"Fibonacci series: ";
for(int i=0;i<num;i++)
{
cout<<fibonacci_series(i)<<" ";
}
cout<<endl;
}
return 0;
}

7. Sum of Natural Numbers


#include<iostream>
using namespace std;
int sum_of_natural_numbers(int num)
{
if(num==0)
{
return 0;
}
else
{
return num+sum_of_natural_numbers(num-1);
}
}
int main()
{
int num,sum;
cout<<"Enter the positive integer."<<endl;
cin>>num;
if(num<0)
{
cout<<"Please enter the number again."<<endl;
cin>>num;
}
else
{
sum=sum_of_natural_numbers(num);
cout<<"Sum of first "<<num<<" natural nuber is: "<<sum<<endl;
}
return 0;
}
Lab No. 10

Course Name: Data Structures and Algorithms


Submitted by: Rabia Sarfraz
Roll No.: 2330-0070
Class Section: FA23/BS(SE)
Submitted to: Sir Bilal
DATE: 08th January, 2025
Practice Task No. 01: Binary Search Tree Recursively
Code:
#include <iostream>
using namespace std;
// Definition of a Node
struct Node{
int value;
Node* left;
Node* right;
//constructor
Node(int data)
{
value = data;
left=right=NULL ;
}
};
// Binary Search Tree Class
class BST{
private:
Node* root;
public:
BST() //constructor
{
root=NULL;
}
//insert function
void insert(int value)
{
root=insertNode(root, value);
}
Node* insertNode(Node* node, int value)
{
if (node==NULL)
{
return new Node(value);
}
if (value<node->value)
{
node->left=insertNode(node->left,value);
} else if (value>node->value)
{
node->right=insertNode(node->right,value);
}
return node;
}
//search function
bool search(int value)
{
return searchNode(root, value);
}
bool searchNode(Node* node,int value)
{
if (node==NULL)
{
return false;
}
if (node->value==value)
{
return true;
}
if (value<node->value)
{
return searchNode(node->left,value);
}
return searchNode(node->right,value);
}
//delete function
void deleteValue(int value)
{
root=deleteNode(root, value);
}
//part of delete fuction
Node* findMin(Node* node)
{
while(node&&node->left!=NULL)
{
node=node->left;
}
return node;
}
Node* deleteNode(Node* node, int value)
{
if (node==NULL)
{
return node;
}
if (value<node->value)
{
node->left=deleteNode(node->left, value);
}
else if (value>node->value)
{
node->right=deleteNode(node->right, value);
}
else
{
// Case 1: Node is a leaf
if (node->left==NULL&&node->right==NULL)
{
delete node;
return NULL;
}
// Case 2: Node has one child (right)
else if (node->left==NULL)
{
Node* temp=node->right;
delete node;
return temp;
}
// Case 3: Node has one child (left)
else if (node->right==NULL)
{
Node* temp=node->left;
delete node;
return temp;
}
// Case 4: Node has two children
else
{
Node* temp=findMin(node->right);
node->value=temp->value;
node->right=deleteNode(node->right, temp->value);
}
}
return node;
}
//inorder printing function
void inorder()
{
inorderTraversal(root);
cout<<endl;
}
void inorderTraversal(Node* node)
{
if (node!=NULL)
{
inorderTraversal(node->left);
cout<<node->value<< " ";
inorderTraversal(node->right);
}
}
//preorder printing function
void preorder()
{
preorderTraversal(root);
cout<<endl;
}
void preorderTraversal(Node* node)
{
if (node!=NULL)
{
cout << node->value << " ";
preorderTraversal(node->left);
preorderTraversal(node->right);
}
}
//postorder printing function
void postorder()
{
postorderTraversal(root);
cout<<endl;
}
void postorderTraversal(Node* node)
{
if (node!=NULL)
{
postorderTraversal(node->left);
postorderTraversal(node->right);
cout<<node->value << " ";
}
}
};
int main()
{
BST tree;
// Inserting values
tree.insert(50);
tree.insert(30);
tree.insert(20);
tree.insert(40);
tree.insert(70);
tree.insert(60);
tree.insert(80);
cout << "In-order traversal before deletion: ";
tree.inorder();
// Searching for a value
int searchValue = 40;
if (tree.search(searchValue))
{
cout << "Value " << searchValue << " found in the tree.\n";
}
else
{
cout << "Value " << searchValue << " not found in the tree.\n";
}
tree.deleteValue(20); // Deleting a leaf node
tree.deleteValue(30); // Deleting a node with one child
tree.deleteValue(50); // Deleting a node with two children
cout << "In-order traversal after deletion: ";
tree.inorder();
cout << "Pre-order traversal: ";
tree.preorder();
cout << "Post-order traversal: ";
tree.postorder();
return 0;
}
Result:
Practice Task NO. 02: Binary Search Tree Iteratively
Code:
#include <iostream>

using namespace std;

struct Node {
int value;
Node* left;
Node* right;
};

class BinarySearchTree {
public:
BinarySearchTree() : root(NULL) {}

void insert(int value) {


Node* newNode = new Node();
newNode->value = value;
newNode->left = NULL;
newNode->right = NULL;

if (root == NULL) {
root = newNode;
} else {
Node* current = root;
while (true) {
if (value < current->value) {
if (current->left == NULL) {
current->left = newNode;
break;
}
current = current->left;
} else {
if (current->right == NULL) {
current->right = newNode;
break;
}
current = current->right;
}
}
}
}

bool search(int value) {


Node* current = root;
while (current != NULL) {
if (value == current->value) {
return true;
} else if (value < current->value) {
current = current->left;
} else {
current = current->right;
}
}
return false;
}

void deleteNode(int value) {


root = deleteNodeRecursive(root, value);
}
Node* deleteNodeRecursive(Node* node, int value) {
if (node == NULL) {
return node;
}

if (value < node->value) {


node->left = deleteNodeRecursive(node->left, value);
} else if (value > node->value) {
node->right = deleteNodeRecursive(node->right, value);
} else {
// node to delete found
// case 1: No child
if (node->left == NULL && node->right == NULL) {
delete node;
node = NULL;
}
// case 2: One child
else if (node->left == NULL) {
Node* temp = node;
node = node->right;
delete temp;
} else if (node->right == NULL) {
Node* temp = node;
node = node->left;
delete temp;
}
// case 3: Two children
else {
Node* temp = findMin(node->right);
node->value = temp->value;
node->right = deleteNodeRecursive(node->right, temp->value);
}
}
return node;
}

Node* findMin(Node* node) {


while (node->left != NULL) {
node = node->left;
}
return node;
}

void inorderTraversal() {
Node* current = root;
while (current != NULL) {
if (current->left == NULL) {
cout << current->value << " ";
current = current->right;
} else {
Node* predecessor = current->left;
while (predecessor->right != NULL && predecessor->right != current) {
predecessor = predecessor->right;
}
if (predecessor->right == NULL) {
predecessor->right = current;
current = current->left;
} else {
predecessor->right = NULL;
cout << current->value << " ";
current = current->right;
}
}
}
}

private:
Node* root;
};

int main() {
BinarySearchTree bst;

bst.insert(8);
bst.insert(3);
bst.insert(10);
bst.insert(1);
bst.insert(6);
bst.insert(14);
bst.insert(4);
bst.insert(7);
bst.insert(13);

cout << "Inorder Traversal: ";


bst.inorderTraversal();
cout << endl;

cout << "Search for 10: " << (bst.search(10) ? "Found" : "Not Found") << endl;

bst.deleteNode(10);

cout << "Inorder Traversal after deletion: ";


bst.inorderTraversal();
cout << endl;

return 0;
}
Result:
Task N0. 01: Create a BST of user-defined values. Keep asking user values
until he/she enters any negative number. Now display the elements of the tree
in In-order, Post-order, and Pre-order form. Your program should also
contain a search function to find a particular number entered by the user. A
search function should be recursive.
Code:
#include <iostream>
using namespace std;
// Definition of a Node
struct Node{
int value;
Node* left;
Node* right;
//constructor
Node(int data)
{
value = data;
left=right=NULL ;
}
};
// Binary Search Tree Class
class BST{
private:
Node* root;
public:
//constructor
BST()
{
root=NULL;
}
//insert function
void insert(int value)
{
root=insertNode(root, value);
}
Node* insertNode(Node* node, int value)
{
if (node==NULL)
{
return new Node(value);
}
if (value<node->value)
{
node->left=insertNode(node->left,value);
} else if (value>node->value)
{
node->right=insertNode(node->right,value);
}
return node;
}
//search function
bool search(int value)
{
return searchNode(root, value);
}
bool searchNode(Node* node,int value)
{
if (node==NULL)
{
return false;
}
if (node->value==value)
{
return true;
}
if (value<node->value)
{
return searchNode(node->left,value);
}
return searchNode(node->right,value);
}
//inorder printing function
void inorder()
{
inorderTraversal(root);
cout<<endl;
}
void inorderTraversal(Node* node)
{
if (node!=NULL)
{
inorderTraversal(node->left);
cout<<node->value<< " ";
inorderTraversal(node->right);
}
}
//preorder printing function
void preorder()
{
preorderTraversal(root);
cout<<endl;
}
void preorderTraversal(Node* node)
{
if (node!=NULL)
{
cout << node->value << " ";
preorderTraversal(node->left);
preorderTraversal(node->right);
}
}
//postorder printing function
void postorder()
{
postorderTraversal(root);
cout<<endl;
}
void postorderTraversal(Node* node)
{
if (node!=NULL)
{
postorderTraversal(node->left);
postorderTraversal(node->right);
cout<<node->value << " ";
}
}
};
int main()
{
BST tree;
int n;
cout<<"Enter numbers. To stop, enter a negative number"<<endl;
for(int i=0;;i++)
{
cout<<"Enter the positive number: ";
cin>>n;
if(n>=0)
{
tree.insert(n);
}
else
{
break;
}
}
cout<<"In-order Traversal: "<<endl;
tree.inorder();
cout << "Pre-order traversal: ";
tree.preorder();
cout << "Post-order traversal: ";
tree.postorder();
cout<<"Enter the number you want to search in tree: ";
cin>>n;
if(tree.search(n))
{
cout<<n<<" has been found in the tree."<<endl;
}
else
{
cout<<n<<" not found in the tree."<<endl;
}
return 0;
}
Result:

Task No. 02: Modify question 1 and add a function in the program called
“Display_less”. Function should ask the user to enter a number and then
display all elements from the tree that are less than or equal to the number.
Note that the number may not be present in the tree.
Code:
#include <iostream>
using namespace std;
// Definition of a Node
struct Node{
int value;
Node* left;
Node* right;
//constructor
Node(int data)
{
value = data;
left=right=NULL ;
}
};
// Binary Search Tree Class
class BST{
private:
Node* root;
public:
//constructor
BST()
{
root=NULL;
}
//insert function
void insert(int value)
{
root=insertNode(root, value);
}
Node* insertNode(Node* node, int value)
{
if (node==NULL)
{
return new Node(value);
}
if (value<node->value)
{
node->left=insertNode(node->left,value);
} else if (value>node->value)
{
node->right=insertNode(node->right,value);
}
return node;
}
//search function
bool search(int value)
{
return searchNode(root, value);
}
bool searchNode(Node* node,int value)
{
if (node==NULL)
{
return false;
}
if (node->value==value)
{
return true;
}
if (value<node->value)
{
return searchNode(node->left,value);
}
return searchNode(node->right,value);
}
//inorder printing function
void inorder()
{
inorderTraversal(root);
cout<<endl;
}
void inorderTraversal(Node* node)
{
if (node!=NULL)
{
inorderTraversal(node->left);
cout<<node->value<< " ";
inorderTraversal(node->right);
}
}
//preorder printing function
void preorder()
{
preorderTraversal(root);
cout<<endl;
}
void preorderTraversal(Node* node)
{
if (node!=NULL)
{
cout << node->value << " ";
preorderTraversal(node->left);
preorderTraversal(node->right);
}
}
//postorder printing function
void postorder()
{
postorderTraversal(root);
cout<<endl;
}
void postorderTraversal(Node* node)
{
if (node!=NULL)
{
postorderTraversal(node->left);
postorderTraversal(node->right);
cout<<node->value << " ";
}
}
//display less function
void displayLess(int n)
{
cout<<"Elements less than or equal to "<<n<<": ";
displayLessThanOrEqual(root, n);
cout<<endl;
}
void displayLessThanOrEqual(Node* node,int n)
{
if (node!=NULL)
{
if (node->value<=n)
{
displayLessThanOrEqual(node->left,n);
cout<<node->value<<" ";
displayLessThanOrEqual(node->right,n);
}
else
{
displayLessThanOrEqual(node->left,n);
}
}
}
};
int main()
{
BST tree;
int n;
cout<<"Enter numbers. To stop, enter a negative number"<<endl;
for(int i=0;;i++)
{
cout<<"Enter the positive number: ";
cin>>n;
if(n>=0)
{
tree.insert(n);
}
else
{
break;
}
}
cout<<"In-order Traversal: "<<endl;
tree.inorder();
cout << "Pre-order traversal: ";
tree.preorder();
cout << "Post-order traversal: ";
tree.postorder();
cout<<"Enter the number you want to search in tree: ";
cin>>n;
if(tree.search(n))
{
cout<<n<<" has been found in the tree."<<endl;
}
else
{
cout<<n<<" not found in the tree."<<endl;
}
cout<<"Enter a number to print all numbers less than it (the number will not
be in the tree): ";
cin>>n;
tree.displayLess(n);
return 0;
}
Result:
Task No. 03: Implement a C++ program to store Strings in the Binary
Search tree. Your program should have the following functions:

 Insert
 Display
 Search

Code:
#include <iostream>
#include<cstring>
using namespace std;
// Definition of a Node
struct Node{
string value;
Node* left;
Node* right;
//constructor
Node(string data)
{
value = data;
left=right=NULL ;
}
};
// Binary Search Tree Class
class BST{
private:
Node* root;
public:
//constructor
BST()
{
root=NULL;
}
//insert function
void insert(string value)
{
root=insertNode(root, value);
}
Node* insertNode(Node* node, string value)
{
if (node==NULL)
{
return new Node(value);
}
if (value<node->value)
{
node->left=insertNode(node->left,value);
} else if (value>node->value)
{
node->right=insertNode(node->right,value);
}
return node;
}
//search function
bool search(string value)
{
return searchNode(root, value);
}
bool searchNode(Node* node,string value)
{
if (node==NULL)
{
return false;
}
if (node->value==value)
{
return true;
}
if (value<node->value)
{
return searchNode(node->left,value);
}
return searchNode(node->right,value);
}
//inorder printing function
void inorder()
{
inorderTraversal(root);
cout<<endl;
}
void inorderTraversal(Node* node)
{
if (node!=NULL)
{
inorderTraversal(node->left);
cout<<node->value<< " ";
inorderTraversal(node->right);
}
}
//preorder printing function
void preorder()
{
preorderTraversal(root);
cout<<endl;
}
void preorderTraversal(Node* node)
{
if (node!=NULL)
{
cout << node->value << " ";
preorderTraversal(node->left);
preorderTraversal(node->right);
}
}
//postorder printing function
void postorder()
{
postorderTraversal(root);
cout<<endl;
}
void postorderTraversal(Node* node)
{
if (node!=NULL)
{
postorderTraversal(node->left);
postorderTraversal(node->right);
cout<<node->value << " ";
}
}
};
int main()
{
BST tree;
tree.insert("ali");
tree.insert("amna");
tree.insert("saima");
tree.insert("wavy");
tree.insert("lays");
tree.insert("chocolate");
string s;
cout<<"Enter string: "<<endl;
getline(cin,s);
tree.insert(s);
cout<<"In-order Traversal: "<<endl;
tree.inorder();
cout << "Pre-order traversal: ";
tree.preorder();
cout << "Post-order traversal: ";
tree.postorder();
cout<<"Enter the number you want to search in tree: ";
getline(cin,s);
if (tree.search(s))
{
cout<<"\""<<s<<"\"has been found in the tree."<<endl;
}
else
{
cout<<"\""<<s<<"\" not found in the tree."<<endl;
}
return 0;
}
Result:

The end!
Lab No. 11

Course Name: Data Structures and Algorithms


Submitted by: Rabia Sarfraz
Roll No.: 2330-0070
Class Section: FA23/BS(SE)
Submitted to: Sir Bilal
DATE: 10th January, 2025
Practice Task No. 01:
Write a program of a general binary tree using an array. Elements of this
array will be objects of person class. Attributes of Book (privately defined) are
1. ISBN (String) (e.g. 1235-123-1)
2. author_name (string)
3. Edition (int)
Book class contains member functions (publicly defined): constructor, input,
and output functions. You must define insert, delete, and search functions for
this binary tree. The insert function should allow the insertion of the object of
the book class at an appropriate location in a general binary tree, and the
delete function should delete an object of the book class from the tree whose
ISBN is specified by the user. A search function should search for an object of
the book class from this tree whose ISBN is specified by the user. You are
required to implement pre-orders, in order and
post order traversal functions for this binary tree.
Code:
#include <iostream>
#include <string>
using namespace std;
struct Book
{
int edition;
string ISBN;
string name;
string author;
};
struct Node
{
Book book;
Node* left;
Node* right;
Node(Book b)
{
book=b;
left=NULL;
right=NULL;
}
};
class BinaryTree
{
private:
Node* root;
public:
BinaryTree()
{
root=NULL;
}
void insert(Book book)
{
root=insertNode(root,book);
}
Node* insertNode(Node* root,Book book)
{
if(root==NULL)
{
return new Node(book);
}
if(book.ISBN<root->book.ISBN)
{
root->left=insertNode(root->left,book);
}
else
{
root->right=insertNode(root->right,book);
}
return root;
}
void search(string isbn)
{
Node* result=searchNode(root,isbn);
if (result)
{
cout<<"Book found: "<<endl;
cout<<"ISBN: "<<result->book.ISBN<<endl<<"Name: "<<result-
>book.name<<endl;
cout<<"Author: "<<result->book.author<<endl<<"Edition:
"<<result->book.edition<<endl;
}
else
{
cout<<"Book not found."<<endl;
}
}
Node* searchNode(Node* root,string isbn)
{
if(root->book.ISBN==isbn)
{
return root;
}
if(isbn<root->book.ISBN)
{
return searchNode(root->left,isbn);
}
else
{
return searchNode(root->right,isbn);
}
}
void deleteBook(string isbn)
{
root=deleteNode(root,isbn);
}
Node* deleteNode(Node* root,string isbn)
{
if(root==NULL)
{
return root;
}
if(isbn<root->book.ISBN)
{
root->left=deleteNode(root->left,isbn);
}
else if(isbn>root->book.ISBN)
{
root->right=deleteNode(root->right,isbn);
}
else if(root->left==NULL&&root->right==NULL) //leaf node
{
delete root;
}
else //one child
{
if(root->left==NULL)
{
Node* temp=root->right;
delete root;
return temp;
}
else if(root->right==NULL)
{
Node* temp=root->left;
delete root;
return temp;
}
else if(root->left!=NULL&&root->right!=NULL)
{ //two children
Node* temp=minValueNode(root->right);
root->book=temp->book;
root->right=deleteNode(root->right,temp->book.ISBN);
}
else
{
return root;
}
}
}
Node* minValueNode(Node* node)
{
Node* current=root;
while(current&&current->left!=NULL)
{
current=current->left;
}
return current;
}
void preorder()
{
cout<<"Pre-order Traversal: "<<endl;
preorder(root);
}
void preorder(Node* root)
{
if (root!=NULL)
{
cout<<"ISBN: "<<root->book.ISBN<<endl<<"Name: "<<root-
>book.name<<endl;
cout<<"Author: "<<root->book.author<<endl<<"Edition:
"<<root->book.edition<<endl;
preorder(root->left);
preorder(root->right);
}
}
void inorder()
{
cout<<"In-order Traversal: "<<endl;
inorder(root);
}
void inorder(Node* root)
{
if(root!= NULL)
{
inorder(root->left);
cout<<"ISBN: "<<root->book.ISBN<<endl<<"Name: "<<root-
>book.name<<endl;
cout<<"Author: "<<root->book.author<<endl<<"Edition:
"<<root->book.edition<<endl;
inorder(root->right);
}
}
void postorder()
{
cout<<"Post-order Traversal: "<<endl;
postorder(root);
}
void postorder(Node* root)
{
if(root!= NULL)
{
postorder(root->left);
postorder(root->right);
cout<<"ISBN: "<<root->book.ISBN<<endl<<"Name: "<<root-
>book.name<<endl;
cout<<"Author: "<<root->book.author<<endl<<"Edition:
"<<root->book.edition<<endl;
}
}
};
int main()
{
BinaryTree tree;
int choice;
while (true)
{
cout<<"Binary Tree Menue:"<<endl;
cout<<"1. Insert a Book"<<endl;
cout<<"2. Delete a Book"<<endl;
cout<<"3. Search a Book"<<endl;
cout<<"4. Pre-order Traversal"<<endl;
cout<<"5. In-order Traversal"<<endl;
cout<<"6. Post-order Traversal"<<endl;
cout<<"7. Exit"<<endl;
cout<<"Enter your choice: ";
cin>>choice;
if(choice==1)
{
Book book;
cout<<"Enter ISBN: ";
cin>>book.ISBN;
cout<<"Enter Book Name: ";
cin.ignore();
getline(cin,book.name);
cout<<"Enter Author Name: ";
cin.ignore();
getline(cin, book.author);
cout<<"Enter Edition: ";
cin>>book.edition;
tree.insert(book);
}
else if(choice==2)
{
string isbn;
cout<<"Enter ISBN of the book to delete: ";
cin>>isbn;
tree.deleteBook(isbn);
}
else if(choice==3)
{
string isbn;
cout<<"Enter ISBN of the book to search: ";
cin>>isbn;
tree.search(isbn);
}
else if(choice==4)
{
tree.preorder();
}
else if(choice==5)
{
tree.inorder();
}
else if(choice==6)
{
tree.postorder();
}
else if(choice==7)
{
cout<<"Exiting program."<<endl;
break;
}
cout << endl;
}
}
Result:

The end!

You might also like