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

Data Structures and Algorithm Lab

The lab report summarizes experiments conducted on data structures and algorithms. It includes 11 problems exploring concepts like arrays, sorting, searching, stacks, and pointers. For each problem, the report provides the problem name, algorithm description in pseudocode, C++ source code, and sample input/output. The problems cover a range of common data structure operations, such as insertion, deletion, sorting with selection, insertion and selection sorts, searching, and stack push and pop operations. The report was submitted to fulfill course requirements for an undergraduate course in information and communication technology.

Uploaded by

Md Elias Khan04
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

Data Structures and Algorithm Lab

The lab report summarizes experiments conducted on data structures and algorithms. It includes 11 problems exploring concepts like arrays, sorting, searching, stacks, and pointers. For each problem, the report provides the problem name, algorithm description in pseudocode, C++ source code, and sample input/output. The problems cover a range of common data structure operations, such as insertion, deletion, sorting with selection, insertion and selection sorts, searching, and stack push and pop operations. The report was submitted to fulfill course requirements for an undergraduate course in information and communication technology.

Uploaded by

Md Elias Khan04
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

Islamic University, Kushtia

Department of Information and Communication


Technology

A Lab Report
On
Data Structure and Algorithm Laboratory
The Lab report is submitted for the partial requirement of course no. ICT-2104

Submitted by Submitted to
Name: Md Elias Khan Dr. Md Alamgir Hossain
Roll: 1918004 Associate Professor
Regi: 1312 Department of Information and
Semester: 2nd year 1st semester Communication Technology
Session: 2019-20 Islamic University, Kushtia

Submission Date: 24 September, 2022


Problem No:01
Problem Name: Write a program to use sorting elements with Selection
Sort.
Algorithm:
Step-1: Start.
Step-2: Set Min to location 0 in step-1.
Step-3: Look for the smallest element on the list.
Step-4: Replace the value at location Min with different value.
Step-5: Increase Min to point to the next element.
Step-6: Continue until the list is Sorted.
Step-7: Stop.
Source Code:
#include <iostream>
using namespace std;
int main()
{
int a[100],n,i,j,position,temp;
cout<<"Enter the number of elements:";
cin>>n;
cout<<"Enter the Numbers:"<<endl;
for (i=0; i<n; i++)
cin>>a[i];
for(i=0; i<n-1; i++)
{
position=i;
for(j=i+1; j<n; j++)
{
if(a[position]>a[j])
position=j;
}
if(position!=i)
{
temp=a[i];
a[i]=a[position];
a[position]=temp;
}
}
cout<<"Sorted array:"<<endl;
for(i=0; i<n; i++)
cout<<a[i]<<endl;
return 0;
}

Input/Output:
Problem no:02
Problem name: Write a program to use sorting elements with Insertion
Sort.
Algorithm:
Step-1: Start
Step-2: Input the elements in an unsorted array
Stp-3: If the element is the first element, assume that it already sorted,
return-1
Step-4: Pick the next element and store it separately in key
Step-4: Now compare the key with all the elements in sorted array
Step-5: If the element in the sorted array is smaller in the current element,
then move to the next element. Else shift greater elements in the array
towards the right
Step-6: Insert the value
Step-7: Repeat until the array is sorted
Step-8: End
Source Code:
//Insertion sort in C++
#include <iostream>
using namespace std;
void before_insertion_printArray(int array[],int size)
{
cout<<"Before Insertion sort,The array elements are:"<<endl;
for(int i=0;i<size;i++)
{
cout<<array[i]<<" ";
}
cout<<endl;
}
void after_insertion_printArray(int array[], int size)
{
for (int i = 0; i < size; i++)
{
cout << array[i] << " ";
}
cout << endl;
}

void insertionSort(int array[], int size)


{
for (int step = 1; step < size; step++)
{
int key = array[step];
int j = step - 1;
while (key < array[j] && j >= 0)
{
array[j + 1] = array[j];
--j;
}
array[j + 1] = key;
}
}
int main()
{
int data[]={9, 5, 1, 4, 3};
int size = sizeof(data) / sizeof(data[0]);
before_insertion_printArray(data,size);
insertionSort(data, size);
cout << "After insertion sort,Sorted array in ascending order:\n";
after_insertion_printArray(data, size);
}

Input/Output:
Problem No: 03
Problem Name: Write a program using array for insertion operation in an
array
Algorithm:
1. Start
2. Get the element value which needs to be inserted
3. Get the position value
4. Check whether the position value is valid or not
5. If it is valid,
Shift all the elements from the last index to position index by 1
position to the right. Insert the new element in array[position].
6. Otherwise, Invalid position.
7. End.

Source Code:
#include<iostream>
using namespace std;
int main()
{
int arr[]={10,20,40,50,60};
int element,position,i;
cout<<"Enter position and element:";
cin>>position>>element;
int size=sizeof(arr)/sizeof (arr[0]);
if(position>=0&&position<=size)
{
for(i=size;i>position;i--)
{
arr[i]=arr[i-1];
}
arr[position]=element;
for(i=0;i<=size;i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
}
else
cout<<"Invalid position";
return 0;
}
Input/Output:

Problem no: 04
Problem Name: Write a program using array for deletion operation in an
array
Algorithm:
1. Start
2. [Initialize counter variable] Set i = position-1
3. Repeat step-4 and step-5 for i = position-1 to i<size
4. [Move ith element backward (left)]. Set a[i] = a[i+1]
5. [Increase counter]. Set i=i+1
6. [End of step-03 loop]
7. [Rest size of the array]. Set size= size-1
8. Stop
Source Code:
#include <iostream>
using namespace std;
int main()
{
int i, size, x, pos;
int a[]= {-1, 87, -68, 10, 8};
size=sizeof(a)/sizeof(a[0]);
cout << "The array elements before deletion operation:"<<endl;
for(i=0; i<size; i++)
cout << "a[" << i << "] = " << a[i]<<endl;
cout << "Enter the position from where you wish to delete the element: ";
cin >> pos;
cout << "The array elements after deletion operation: "<<endl;
for(i=pos-1; i<size; i++)
a[i]=a[i+1];
size = size - 1;
for(i=0; i<size; i++)
cout << "a[" << i << "] = " << a[i]<<endl;
return 0;
}
Input/Output:

Problem no: 05
Problem Name: Write a program using array for searching operation in
an array
Algorithm:
1. Start
2. Iterate the array using loop
3. Check whether the given key is present, a[i]=key
4. If yes,
Print “Search Found”
5. Else
Print “Not Found”
6. Stop
Source Code:
#include<iostream>
using namespace std;
int main()
{
int arr[]={34, 2, 23, 100, 60};
int key,i,flag = 0;
cout<<"Enter the element to search:";
cin>>key;
int size=sizeof(arr)/sizeof(arr[0]);
for(i=0;i<size;i++)
{
if(arr[i]==key)
{
flag = 1;
break;
}
}
if(flag == 1)
cout<<"Search Found";
else
cout<<"Search not Found";
return 0;
}
Input/Output:

Problem No: 06
Problem Name: Write a program using array for update operation in an
array.
Algorithm:
1. Start
2. Set LA[k-1] = item
3. End
Source Code:
#include<iostream>
using namespace std;
int main()
{
int LA[]={1,3,5,7,8};
int k,item;
int i,j;
int size=sizeof(LA)/sizeof(LA[0]);
cout<<"The original array elements are:"<<endl;
for(i=0;i<size;i++)
{
cout<<LA[i]<<endl;
}
cout<<"Enter the position:";
cin>>k;
cout<<"Enter the item:";
cin>>item;
LA[k-1]=item;
cout<<"The array elements after update:"<<endl;
for(i=0;i<size;i++)
{
cout<<LA[i]<<endl;
}
return 0;
}
Input/Output:

Problem No: 07
Problem Name: Write a program using Stack for Push operation
Algorithm:
1.Start
2. If Top=Max-1
Print Overflow: “Stack is Full” and Exit
Else Top= Top+1
3.Stack [Top]= Element
4.End
Source Code:
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack<int> mystack;
mystack.push(0);
mystack.push(1);
mystack.push(2);
while (!mystack.empty())
{
cout<< mystack.top()<<endl;
mystack.pop();
}
return 0;
}
Input/Output:

Problem No: 08
Problem Name: Write a program using Stack for Pop operation.
Algorithm:
Step 1: If TOP=-1
Print “Underflow: Stack is empty” and Exit
End if
Step 2: Set Del_element = Stack [Top]
Step 3: Top=Top-1
Step 4: Return Del_Element
Step 5: End
Source Code:
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack<int> mystack;
mystack.push(1);
mystack.push(2);
mystack.push(3);
mystack.push(4);
mystack.pop();
mystack.pop();
while (!mystack.empty())
{
cout<< mystack.top()<<endl;
mystack.pop();
}
return 0;
}
Input/Output:

Problem No:09
Problem Name: Write a program using pointer for Print Address of a
variables.
Algorithm:
1. Start
2. Declare variables and pointer variables of the program
3. Take the input from the user.
4. Print the number using pointer
5. Print the address using pointer.
6. End
Source Code:
#include<iostream>
using namespace std;
int main()
{
int a;
int *pt;
cout<<"Pointer Example Program : Print Pointer Address:"<<endl;
a = 10;
pt = &a;
cout<<"[a]:Value of A:"<<a<<endl;
cout<<"[*pt]:Value of A:"<<*pt<<endl;
cout<<"[&a]:Address of A:"<<&a<<endl;
cout<<"[pt]:Address of A:"<<pt<<endl;
cout<<"[&pt]:Address of pt:"<< &pt<<endl;
cout<<"[pt]:Value of pt:"<<pt<<endl;
return 0;
}

Input/Output:

Problem No: 10
Problem Name: Write a program using pointer for Print the values of a
pointer variables.
Algorithm:
1. Start
2. Declare the pointer variables
3. Assign the value of pointer variables
4. Print the value and address
5. Stop.
Source Code:
#include<iostream>
using namespace std;
int main()
{
int *ptr;
int p;
p=30;
ptr=&p;
cout<<"Value of pointer variables:"<<*ptr<<endl;
cout<<"Address of pointer variables:"<<ptr<<endl;
return 0;
}

Input/Output:

Problem No: 11
Problem Name: Write a program using pointer for Changing value using
pointer variables.
Algorithm:
1.Start
2.Declare the function name (change).
3.Declare and initialize two variables
4.Call the function
Temp=x
X=y
Y=temp
5.Display the value
6.Stop
Source Code:
#include<iostream>
using namespace std;
void change(int *x,int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
int main()
{
int a=10;
int b=20;
cout<<"Before changing the value is:"<<a<<" "<<b<<endl;
change(&a,&b);
cout<<"After changing the value is:"<<a<<" "<<b<<endl;
return 0;
}
Input/Output:

Problem No: 12
Problem Name: Write a program using pointer for Pointer to Array.
Algorithm:
1. Start
2. Declare and definition an array
3. Declare pointer variables
4. Set i and initialize it
5. Print the address of array variables
6. Print the address of pointer variables
7. Print the value of variables
8. Stop
Source Code:
#include <iostream>
using namespace std;
int main()
{
float arr[3]={9,6,7};
// declare pointer variable
float *ptr;
cout << "Displaying address using arrays: " << endl;
for (int i = 0; i < 3; ++i)
{
cout << "&arr[" << i << "] = " << &arr[i] << endl;
}
cout<<endl;
// ptr = &arr[0]
ptr = arr;
cout<<"Displaying address using pointers: "<< endl;
for (int i = 0; i < 3; ++i)
{
cout << "ptr + " << i << " = "<< ptr + i << endl;
}
cout <<endl;
for (int i = 0; i < 3; ++i)
{
cout << "ptr + " << i << " = "<< *(ptr + i) << endl;
}
cout <<endl;
return 0;
}
Input/output:

Problem No: 13
Problem Name: Write a program using pointers for call by reference and
call by address.
Algorithm:
1. Start
2. Declare and initialize the variables
3. Declare swap function
4. Call the swap function with address
Declare temp variable
Temp=*n1
*n1=*n2
*n2=temp
5. Display the output
6. Stop
Source Code:
#include <iostream>
using namespace std;
// function prototype with pointer as parameters
void swap(int*, int*);
int main()
{
// initialize variables
int a = 1, b = 2;
cout << "Before swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
// call function by passing variable addresses
swap(&a, &b);
cout << "\nAfter swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}
// function definition to swap numbers
void swap(int* n1, int* n2) {
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}
Input/Output:

Problem No: 14
Problem Name: Write a program using pointers for pointer structure.
Algorithm:
1. Start
2. Declare the variables
3. Get the input from user
4. Create pointer type Structure
5. Print the output
6. End.
Source Code:
#include <iostream>
using namespace std;
struct Distance
{
int feet;
float inch;
};

int main()
{
Distance *ptr, d;
ptr = &d;
cout << "Enter feet: ";
cin >> (*ptr).feet;
cout << "Enter inch: ";
cin >> (*ptr).inch;
//cin >> ptr->inch;
cout << "Displaying information." << endl;
cout << "Distance = " << (*ptr).feet << " feet " << (*ptr).inch << " inches";
cout<<endl;
return 0;
}
Input/Output:

Problem No: 15
Problem Name: Write a program using Linked list for Traverse operation.
Algorithm:

Step 1: [INITIALIZE] SET PTR = HEAD


Step 2: Repeat Steps 3 and 4 while PTR! = NULL
Step 3: Apply process to PTR -> DATA
Step 4: SET PTR = PTR->NEXT
[END OF LOOP]
Step 5: EXIT
Source Code:
// Linked list implementation in C
#include <stdio.h>
#include <stdlib.h>
// Creating a node
struct node {
float value;
struct node *next;
};
// print the linked list value
void printLinkedlist(struct node *p) {
while (p != NULL) {
printf("%f ", p->value);
p = p->next;
}
}

int main() {
// Initialize nodes
struct node *head;
struct node *one = NULL;
struct node *two = NULL;
struct node *three = NULL;
// Allocate memory
one = malloc(sizeof(struct node));
two = malloc(sizeof(struct node));
three = malloc(sizeof(struct node));

// Assign value values


one->value = 10.50;
two->value = 20.80;
three->value = 50.50;
// Connect nodes
one->next = two;
two->next = three;
three->next = NULL;
// printing node-value
head = one;
printLinkedlist(head);
printf("\n");
return 1;
}
Input/Output:

Problem No: 16
Problem Name: Write a program using Linked list for Insert node at the
beginning.
Algorithm:

Step 1: IF AVAIL = NULL


Write OVERFLOW
Go to Step 7
[END OF IF]
Step 2: SET NEW_NODE = AVAIL
Step 3: SET AVAIL = AVAIL NEXT
Step 4: SET DATA = VAL
Step 5: SET NEW_NODE NEXT = START
Step 6: SET START = NEW_NODE
Step 7: EXIT

Source Code:
// Linked list implementation in C
#include <stdio.h>
#include <stdlib.h>
// Creating a node
struct node
{
int value;
struct node *next;
};

// print the linked list value


void printLinkedlist(struct node *p)
{
while (p != NULL)
{
printf("%d ", p->value);
p = p->next;
}
}

int main()
{
// Initialize nodes
struct node *head;
struct node *one = NULL;
struct node *two = NULL;
struct node *three = NULL;

// Allocate memory
one = malloc(sizeof(struct node));
two = malloc(sizeof(struct node));
three = malloc(sizeof(struct node));

// Assign value values


one->value = 500;
two->value = 200;
three->value = 350;
// Connect nodes
one->next = two;
two->next = three;
three->next = NULL;

// printing node-value
head = one;
printf("Before Inserting node:\n");
printLinkedlist(head);

//insert at the begining


struct node *newNode;
newNode = malloc (sizeof(struct node));
newNode->value = 4;
newNode->next = head;
head = newNode;

printf("\nLinked List after insertion at the begining: \n");


printLinkedlist(head);
printf("\n");
return 0;
}
Input/Output:

Problem No: 17
Problem Name: Write a program using Linked list for insert node at Middle
Algorithm:

Source Code:
#include <stdio.h>
#include <stdlib.h>
// Creating a node
struct node {
int value;
struct node *next;
};
// print the linked list value
void printLinkedlist(struct node *p) {
while (p != NULL) {
printf("%d ", p->value);
p = p->next;
}
}
int main()
{
// Initialize nodes
struct node *head;
struct node *one = NULL;
struct node *two = NULL;
struct node *three = NULL;
// Allocate memory
one = malloc(sizeof(struct node));
two = malloc(sizeof(struct node));
three = malloc(sizeof(struct node));
// Assign value values
one->value = 45;
two->value = 25;
three->value =30;
// Connect nodes
one->next = two;
two->next = three;
three->next = NULL;
// printing node-value
printf("Before inserting the node:\n");
head = one;
printLinkedlist(head);
//insert at the middle
struct node *newNode;
newNode = malloc(sizeof(struct node));
newNode->value = 40;

struct node *temp = head;


size_t position=3;
for(int i=2; i < position; i++) {
if(temp->next != NULL) {
temp = temp->next;
}
}
newNode->next = temp->next;
temp->next = newNode;

printf("\nLinked List after insertion at the middle: \n");


printLinkedlist(head);
printf("\n");
return 0;
}
Input/Output:
Problem No: 18
Problem Name: Write a program using Linked list for insert node at End.
Algorithm:

Step 1: IF AVAIL = NULL


Write OVERFLOW
Go to Step 10
[END OF IF]
Step 2: SET NEW_NODE = AVAIL
Step 3: SET AVAIL = AVAIL -> NEXT
Step 4: SET NEW_NODE -> DATA = VAL
Step 5: SET NEW_NODE -> NEXT = NULL
Step 6: SET PTR = START
Step 7: Repeat Step 8 while PTR -> NEXT != NULL
Step 8: SET PTR = PTR -> NEXT
[END OF LOOP]
Step 9: SET PTR -> NEXT = NEW_NODE
Step 10: EXIT

Source Code:
#include <stdio.h>
#include <stdlib.h>
// Creating a node
struct node {
int value;
struct node *next;
};
// print the linked list value
void printLinkedlist(struct node *p) {
while (p != NULL) {
printf("%d ", p->value);
p = p->next;
}
}

int main() {
// Initialize nodes
struct node *head;
struct node *one = NULL;
struct node *two = NULL;
struct node *three = NULL;
// Allocate memory
one = malloc(sizeof(struct node));
two = malloc(sizeof(struct node));
three = malloc(sizeof(struct node));
// Assign value values
one->value = 100;
two->value = 200;
three->value =300;
// Connect nodes
one->next = two;
two->next = three;
three->next = NULL;
// printing node-value
printf("Before inserting node at end:\n");
head = one;
printLinkedlist(head);
//insert at the end
struct node *newNode;
newNode = malloc(sizeof(struct node));
newNode->value =400;
newNode->next = NULL;

struct node *temp = head;


while(temp->next != NULL){
temp = temp->next;
}

temp->next = newNode;

printf("\nLinked List after insertion at the end: \n");


printLinkedlist(head);
printf("\n");
return 0;
}
Input/Output:
Problem No: 19
Problem Name: Write a program using Linked list for Delete node at the
Beginning.
Algorithm:
• Step 1:
IF HEAD = NULL
Write UNDERFLOW
Go to Step 5
• Step 2: SET PTR = HEAD
• Step 3: SET HEAD = HEAD -> NEXT
• Step 4: FREE PTR
• Step 5: EXIT

Source Code:
#include <stdio.h>
#include <stdlib.h>
// Creating a node
struct node {
int value;
struct node *next;
};
// print the linked list value
void printLinkedlist(struct node *p) {
while (p != NULL) {
printf("%d ", p->value);
p = p->next;
}
}
int main() {
// Initialize nodes
struct node *head;
struct node *one = NULL;
struct node *two = NULL;
struct node *three = NULL;
struct node *four = NULL;
// Allocate memory
one = malloc(sizeof(struct node));
two = malloc(sizeof(struct node));
three = malloc(sizeof(struct node));
four = malloc(sizeof(struct node));
// Assign value values
one->value = 10;
two->value = 20;
three->value =50;
four->value = 40;
// Connect nodes
one->next = two;
two->next = three;
three->next = four;
four->next = NULL;
// printing node-value
head = one;
//Printing before deletion
printf("Printing before deletion\n");
printLinkedlist(head);
printf("\n");
// Deleting from the begining
head = head->next;
//Printing after deletion
printf("\nPrinting after deletion\n");
printLinkedlist(head);
printf("\n");
return 0;
}
Input/Output:

Problem no: 20
Problem Name: Write a program using Linked list for Delete node at the
Middle.
Algorithm:
Source Code:
#include <stdio.h>
#include <stdlib.h>
// Creating a node
struct node {
int value;
struct node *next;
};
// print the linked list value
void printLinkedlist(struct node *p) {
while (p != NULL) {
printf("%d ", p->value);
p = p->next;
}
}

int main() {
// Initialize nodes
struct node *head;
struct node *one = NULL;
struct node *two = NULL;
struct node *three = NULL;
struct node *four = NULL;
// Allocate memory
one = malloc(sizeof(struct node));
two = malloc(sizeof(struct node));
three = malloc(sizeof(struct node));
four = malloc(sizeof(struct node));
// Assign value values
one->value = 100;
two->value = 200;
three->value = 300;
four->value = 400;
// Connect nodes
one->next = two;
two->next = three;
three->next = four;
four->next = NULL;
// printing node-value
head = one;
//Printing before deletion
printf("Printing before deletion\n");
printLinkedlist(head);
printf("\n");
// Deleting from the middle
int position=3;
struct node* temp = head;
for(int i=2; i< position; i++) {
if(temp->next!=NULL) {
temp = temp->next;
}
}

temp->next = temp->next->next;
//Printing after deletion
printf("\nPrinting after deletion\n");
printLinkedlist(head);
printf("\n");
return 0;
}
Input/Output:

Problem No: 21
Problem Name: Write a program using Linked list for Delete node at the
End.
Algorithm:

Step 1: IF START = NULL


Write UNDERFLOW
Go to Step 7
[END OF IF]
Step 2: SET PTR = START
Step 3: Repeat Step 4 while PTR NEXT! = NULL
Step 4: SET PTR = PTR NEXT
[END OF LOOP]
Step 5: SET PTR PREV NEXT = NULL
Step 6: FREE PTR
Step 7: EXIT
Source Code:
#include <stdio.h>
#include <stdlib.h>
// Creating a node
struct node {
int value;
struct node *next;
};
// print the linked list value
void printLinkedlist(struct node *p) {
while (p != NULL) {
printf("%d ", p->value);
p = p->next;
}
}

int main() {
// Initialize nodes
struct node *head;
struct node *one = NULL;
struct node *two = NULL;
struct node *three = NULL;
struct node *four = NULL;
// Allocate memory
one = malloc(sizeof(struct node));
two = malloc(sizeof(struct node));
three = malloc(sizeof(struct node));
four = malloc(sizeof(struct node));
// Assign value values
one->value = 100;
two->value = 200;
three->value = 300;
four->value = 400;
// Connect nodes
one->next = two;
two->next = three;
three->next = four;
four->next = NULL;
// printing node-value
head = one;
//Printing before deletion
printf("Printing before deletion\n");
printLinkedlist(head);
printf("\n");
// Deleting from the end
struct node* temp = head;
while(temp->next->next!=NULL){
temp = temp->next;
}
temp->next = NULL;
//Printing after deletion
printf("Printing after deletion\n");
printLinkedlist(head);
printf("\n");
return 0;
}
Input/Output:

Problem No: 22
Problem Name: Write a program using vector for Initialization of Vector.
Algorithm:
Source Code:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// initializer list
vector<int> vector1 = {1, 2, 3, 4, 5};
// uniform initialization
vector<int> vector2 {6, 7, 8, 9, 10};
// method 3
vector<int> vector3(5, 12);
cout << "vector1 = ";
// ranged loop
for (const int& i : vector1)
{
cout << i << " ";
}
cout<<endl;
cout << "vector2 = ";
// ranged loop
for (const int& i : vector2) {
cout << i << " ";
}
cout<<endl;
cout << "vector3 = ";
// ranged loop
for (int i : vector3)
{
cout << i << " ";
}
return 0;
}
Input/Output:

Problem No: 23
Problem Name: Write a program using Vector for Add element into a
Vector.
Algorithm:
Source Code:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> num {1, 2, 3, 4, 5};
cout << "Initial Vector: ";
for (const int& i : num)
{
cout << i << " ";
}
cout<<endl;
// add the integers 6 and 7 to the vector
num.push_back(6);
num.push_back(7);
cout << "Updated Vector: ";
for (const int& i : num)
{
cout << i << " ";
}
cout<<endl;
return 0;
}
Input/Output:

Problem No: 23
Problem Name: Write a program using Vector access element of Vector.
Algorithm:
Source Code:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> num {1, 2, 3, 4, 5};
cout << "Element at Index 0: " << num.at(0) << endl;
cout << "Element at Index 2: " << num.at(2) << endl;
cout << "Element at Index 4: " << num.at(4);
vector<int> num1 {1, 2, 3};
cout<<endl;
// gives garbage value
cout <<"Element at Index 4 by [4]:"<<num1[4];
// throws an exception
cout << num1.at(4);
cout<<endl;
return 0;
}
Input/Output:

Problem No:24
Problem Name: Write a program using Vector Update a vector element.
Algorithm:
Source Code:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> num {1, 2, 3, 4, 5};
cout << "Initial Vector: ";
for (const int& i : num) {
cout << i << " ";
}
cout<<endl;
// change elements at indexes 1 and 4
num.at(1) = 9;
num.at(4) = 7;
cout << "\nUpdated Vector: ";
for (const int& i : num) {
cout << i << " ";
}
return 0;
}
Input/Output:

Problem No: 25
Problem Name: Write a program using Vector Delete an element of a
vector.
Algorithm:
Source Code:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> prime_numbers{2, 3, 5, 7};
// initial vector
cout << "Initial Vector: ";
for (int i : prime_numbers)
{
cout << i << " ";
}
cout<<endl;
// remove the last element
prime_numbers.pop_back();
// final vector
cout << "Updated Vector: ";
for (int i : prime_numbers)
{
cout << i << " ";
}
cout<<endl;
return 0;
}
Input/Output:

Problem No: 26
Problem Name: Write a program using Vector iterator to print the Vectors
elements.
Algorithm:
Source Code:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> num {1, 2, 3, 4, 5};
// declare iterator
vector<int>::iterator iter;
// use iterator with for loop
for (iter = num.begin(); iter != num.end(); ++iter)
{
cout << *iter << " ";
}
// vector<int>::iterator iter2;
//iter2 =num.end()-1;
// cout<< *iter2<< endl;
cout<<endl;
return 0;
}
Input/Output:

Problem No: 27
Problem Name: Write a program using Function template for adding an
element using ranged for loop.
Algorithm:
Source Code:
#include <iostream>
using namespace std;
template <typename T>
T add(T num1, T num2)
{
return (num1 + num2);
}

int main() {
int result1;
double result2;
// calling with int parameters
result1 = add<int>(2, 3);
cout << "2 + 3 = " << result1 << endl;
// calling with double parameters
result2 = add<double>(2.2, 3.3);
cout << "2.2 + 3.3 = " << result2 << endl;

return 0;
}
Input/Output:

Problem No: 28
Problem Name: Write a program using Class Template adding an element
using ranged for loop
Algorithm:
Source Code:
#include<iostream>
using namespace std;
template<class T> T add(T &a,T &b)
{
T result=a+b;
return result;
}
int main()
{
int i=2;
int j=3;
float m=2.3;
float n=1.2;
cout<<"Addition of i and j is :"<<add(i,j);
cout<<endl;
cout<<"Addition of m and n is :"<<add(m,n);
return 0;
}
Input/Output:

Problem No: 29
Problem Name: Write a program using Class template for Using multiple
Parameter to add two elements
Algorithm:
Source Code:
#include<iostream>
using namespace std;
// Class template with two parameters
template<class T1, class T2>
class Test
{
T1 a;
T2 b;
public:
Test(T1 x, T2 y)
{
a = x;
b = y;
}
void show()
{
cout << a << " and " << b << endl;
}
};
int main()
{
// instantiation with float and int type
Test <float, int> test1 (1.23, 123);
// instantiation with float and char type
Test <int, char> test2 (100, 'W');
test1.show();
test2.show();
return 0;
}
Input/Output:

Problem No: 30
Problem Name: Write a program to print tree elements using in order
Traversal.
Algorithm:
1. Traverse the left subtree, i.e., call Inorder(left-subtree)
2. Visit the root.
3. Traverse the right subtree, i.e., call Inorder(right-subtree)

Source Code:
#include<iostream>
using namespace std;
struct node {
int data;
struct node *left;
struct node *right;
};
struct node *createNode(int val) {
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->data = val;
temp->left = temp->right = NULL;
return temp;
}
void inorder(struct node *root) {
if (root != NULL) {
inorder(root->left);
cout<<root->data<<" ";
inorder(root->right);
}
}
struct node* insertNode(struct node* node, int val) {
if (node == NULL) return createNode(val);
if (val < node->data)
node->left = insertNode(node->left, val);
else if (val > node->data)
node->right = insertNode(node->right, val);
return node;
}
int main() {
struct node *root = NULL;
root = insertNode(root, 4);
insertNode(root, 5);
insertNode(root, 2);
insertNode(root, 9);
insertNode(root, 1);
insertNode(root, 3);
cout<<"In-Order traversal of the Binary Search Tree is: ";
inorder(root);
return 0;
}
Input/Output:

Problem No: 31
Problem Name: Write a program to print tree elements using Pre-Order
Traversal.
Algorithm:

Step 1: Repeat Steps 2 to 4 while TREE! = NULL


Step 2: Write TREE DATA
Step 3: PREORDER (TREE LEFT)
Step 4: PREORDER (TREE RIGHT) [END OF LOOP]
Step 5: END

Source Code:
#include<iostream>
using namespace std;
struct node {
int data;
struct node *left;
struct node *right;
};
struct node *createNode(int val) {
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->data = val;
temp->left = temp->right = NULL;
return temp;
}
void preorder(struct node *root) {
if (root != NULL) {
cout<<root->data<<" ";
preorder(root->left);
preorder(root->right);
}
}
struct node* insertNode(struct node* node, int val) {
if (node == NULL) return createNode(val);
if (val < node->data)
node->left = insertNode(node->left, val);
else if (val > node->data)
node->right = insertNode(node->right, val);
return node;
}
int main()
{
struct node *root = NULL;
root = insertNode(root, 4);
insertNode(root, 5);
insertNode(root, 2);
insertNode(root, 9);
insertNode(root, 1);
insertNode(root, 3);
cout<<"Pre-Order traversal of the Binary Search Tree is: ";
preorder(root);
return 0;
}
Input/Output:

Problem No: 32
Problem Name: Write a program to print elements using Post-Order
Traversal.
Algorithm:
1. Traverse the left subtree, i.e., call Postorder(left-subtree)
2. Traverse the right subtree, i.e., call Postorder(right-subtree)
3. Visit the root
Source Code:
#include<iostream>
using namespace std;
struct node {
int data;
struct node *left;
struct node *right;
};
struct node *createNode(int val) {
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->data = val;
temp->left = temp->right = NULL;
return temp;
}
void postorder(struct node *root) {
if (root != NULL) {
postorder(root->left);
postorder(root->right);
cout<<root->data<<" ";
}
}
struct node* insertNode(struct node* node, int val) {
if (node == NULL) return createNode(val);
if (val < node->data)
node->left = insertNode(node->left, val);
else if (val > node->data)
node->right = insertNode(node->right, val);
return node;
}
int main() {
struct node *root = NULL;
root = insertNode(root, 4);
insertNode(root, 5);
insertNode(root, 2);
insertNode(root, 9);
insertNode(root, 1);
insertNode(root, 3);
cout<<"Post-Order traversal of the Binary Search Tree is: ";
postorder(root);
return 0;
}
Input/Output:

Problem No: 33
Problem Name: Write a program to check Full Binary Tree or not.
Algorithm:
1. If a binary tree node is NULL then it is a full binary tree.
2. If a binary tree node does have empty left and right sub-trees, then it
is a full binary tree by definition.
3. If a binary tree node has left and right sub-trees, then it is a part of a
full binary tree by definition. In this case recursively check if the left
and right sub-trees are also binary trees themselves.
4. In all other combinations of right and left sub-trees, the binary tree is
not a full binary tree.
Source Code:
#include <bits/stdc++.h>
using namespace std;
/* Tree node structure */
struct Node
{
int key;
struct Node *left, *right;
};

/* Helper function that allocates a new node with the


given key and NULL left and right pointer. */
struct Node *newNode(char k)
{
struct Node *node = new Node;
node->key = k;
node->right = node->left = NULL;
return node;
}

/* This function tests if a binary tree is a full binary tree. */


bool isFullTree (struct Node* root)
{
// If empty tree
if (root == NULL)
return true;

// If leaf node
if (root->left == NULL && root->right == NULL)
return true;

// If both left and right are not NULL, and left & right subtrees
// are full
if ((root->left) && (root->right))
return (isFullTree(root->left) && isFullTree(root->right));

// We reach here when none of the above if conditions work


return false;
}

// Driver Program
int main()
{
struct Node* root = NULL;
root = newNode(10);
root->left = newNode(20);
root->right = newNode(30);

root->left->right = newNode(40);
root->left->left = newNode(50);
root->right->left = newNode(60);
root->right->right = newNode(70);

root->left->left->left = newNode(80);
root->left->left->right = newNode(90);
root->left->right->left = newNode(80);
root->left->right->right = newNode(90);
root->right->left->left = newNode(80);
root->right->left->right = newNode(90);
root->right->right->left = newNode(80);
root->right->right->right = newNode(90);

if (isFullTree(root))
cout << "The Binary Tree is full\n";
else
cout << "The Binary Tree is not full\n";

return 0;
}
Input/Output:
Problem No: 34
Problem Name: Write a program to check Perfect Binary Tree or not
Algorithm:
Source Code:
#include<bits/stdc++.h>

/* Tree node structure */


struct Node
{
int key;
struct Node *left, *right;
};

// Returns depth of leftmost leaf.


int findADepth(Node *node)
{
int d = 0;
while (node != NULL)
{
d++;
node = node->left;
}
return d;
}
/* This function tests if a binary tree is perfect
or not. It basically checks for two things :
1) All leaves are at same level
2) All internal nodes have two children */
bool isPerfectRec(struct Node* root, int d, int level = 0)
{
// An empty tree is perfect
if (root == NULL)
return true;

// If leaf node, then its depth must be same as


// depth of all other leaves.
if (root->left == NULL && root->right == NULL)
return (d == level+1);

// If internal node and one child is empty


if (root->left == NULL || root->right == NULL)
return false;

// Left and right subtrees must be perfect.


return isPerfectRec(root->left, d, level+1) &&
isPerfectRec(root->right, d, level+1);
}

// Wrapper over isPerfectRec()


bool isPerfect(Node *root)
{
int d = findADepth(root);
return isPerfectRec(root, d);
}

/* Helper function that allocates a new node with the


given key and NULL left and right pointer. */
struct Node *newNode(int k)
{
struct Node *node = new Node;
node->key = k;
node->right = node->left = NULL;
return node;
}

// Driver Program
int main()
{
struct Node* root = NULL;
root = newNode(10);
root->left = newNode(20);
root->right = newNode(30);

root->left->left = newNode(40);
root->left->right = newNode(50);
root->right->left = newNode(60);
root->right->right = newNode(70);

if (isPerfect(root))
printf("Yes\n");
else
printf("No\n");

return(0);
}
Input/Output:

Problem No: 35
Problem Name: Write a program with Binary Search Tree
Algorithm:
• The left subtree of a node contains only nodes with keys lesser than the node’s
key.
• The right subtree of a node contains only nodes with keys greater than the
node’s key.
• The left and right subtree each must also be a binary search tree
Source Code:
// Simple program to create a BST of integers and search an element in it
#include<iostream>
using namespace std;
//Definition of Node for Binary search tree
struct BstNode {
int data;
BstNode* left;
BstNode* right;
};

// Function to create a new Node in heap


BstNode* GetNewNode(int data) {
BstNode* newNode = new BstNode();
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}

// To insert data in BST, returns address of root node


BstNode* Insert(BstNode* root,int data) {
if(root == NULL) { // empty tree
root = GetNewNode(data);
}
// if data to be inserted is lesser, insert in left subtree.
else if(data <= root->data) {
root->left = Insert(root->left,data);
}
// else, insert in right subtree.
else {
root->right = Insert(root->right,data);
}
return root;
}
//To search an element in BST, returns true if element is found
bool Search(BstNode* root,int data) {
if(root == NULL) {
return false;
}
else if(root->data == data) {
return true;
}
else if(data <= root->data) {
return Search(root->left,data);
}
else {
return Search(root->right,data);
}
}
int main() {
BstNode* root = NULL; // Creating an empty tree
/*Code to test the logic*/
root = Insert(root,15);
root = Insert(root,10);
root = Insert(root,20);
root = Insert(root,25);
root = Insert(root,8);
root = Insert(root,12);
// Ask user to enter a number.
int number;
cout<<"Enter number be searched\n";
cin>>number;
//If number is found, print "FOUND"
if(Search(root,number) == true) cout<<"Found"<<endl;
else cout<<"Not Found"<<endl;
return 0;
}
Input/Output:
Problem No: 36
Problem Name: Write a program with AdjacencyList
Algorithm:
Begin
for all vertices u in (V - start) do
dist[u] := ∞
prev[u] := φ
done

set dist[start] = 0 and prev[start] := φ

for all node u in V do


insert u into queue ‘Q’.
done

while Q is not empty do


u := minimum element from Queue
delete u from Q
insert u into set S

for each node v adjacent with node u do


if dist[u]+cost(v) < dist[v] then
dist[v] := dist[u]+cost(v)
prev[v] := u
done
done
End
Source Code:
#include <bits/stdc++.h>
using namespace std;
// Function to add edges
void addEdge(vector<int> adj[], int u, int v)
{
adj[u].push_back(v);
}
// Function to print adjacency list
void adjacencylist(vector<int> adj[], int V)
{
for (int i = 0; i < V; i++) {
cout << i << "->";
for (int& x : adj[i]) {
cout << x << " ";
}
cout << endl;
}
}

// Function to initialize the adjacency list


// of the given graph
void initGraph(int V, int edges[3][2], int noOfEdges)
{
// To represent graph as adjacency list
vector<int> adj[V];

// Traverse edges array and make edges


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

// Function call to make an edge


addEdge(adj, edges[i][0], edges[i][1]);
}

// Function Call to print adjacency list


adjacencylist(adj, V);
}

// Driver Code
int main()
{
// Given vertices
int V = 3;

// Given edges
int edges[3][2] = { { 0, 1 }, { 1, 2 }, { 2, 0 } };

int noOfEdges = 3;

// Function Call
initGraph(V, edges, noOfEdges);

return 0;
}
Input/Output:

Problem No: 37
Problem Name: Write a program with AdjacencyMatrix
Algorithm:
add_edge(u, v)
Input: The u and v of an edge {u,v}
Output: Adjacency matrix of the graph G.

Source Code:
#include<iostream>
using namespace std;
int vertArr[20][20]; //the adjacency matrix initially 0
int count = 0;
void displayMatrix(int v) {
int i, j;
for(i = 0; i < v; i++) {
for(j = 0; j < v; j++) {
cout << vertArr[i][j] << " ";
}
cout << endl;
}
}
void add_edge(int u, int v)
{ //function to add edge into the matrix
vertArr[u][v] = 1;
vertArr[v][u] = 1;
}
int main(int argc, char* argv[])
{
int v = 6; //there are 6 vertices in the graph
add_edge(0, 4);
add_edge(0, 3);
add_edge(1, 2);
add_edge(1, 4);
add_edge(1, 5);
add_edge(2, 3);
add_edge(2, 5);
add_edge(5, 3);
add_edge(5, 4);
displayMatrix(v);
return 0;
}
Input/Output:

You might also like