ASSIGNMENT 2
Q1) Write a program to statically allocate a 1-D array of size n to store
data. Write functions to perform insertion, deletion and display operation.
Code:
#include <iostream>
using namespace std;
template <class T>
class StaticArray {
T arr[100];
int n;
public:
StaticArray(int size) { n = size; }
void setData() {
cout << "Enter " << n << " elements:\n";
for (int i = 0; i < n; i++) cin >> arr[i];
}
void insertAt(int pos, T val) {
for (int i = n; i > pos; i--) arr[i] = arr[i - 1];
arr[pos] = val;
n++;
}
void deleteAt(int pos) {
for (int i = pos; i < n - 1; i++) arr[i] = arr[i + 1];
n--;
}
void display() {
for (int i = 0; i < n; i++) cout << arr[i] << " ";
cout << endl;
}
};
int main() {
StaticArray<int> a(5);
[Link]();
cout << "Initial Array: ";
[Link]();
[Link](2, 99);
cout << "After Inserting 99 at index 2: ";
[Link]();
[Link](3);
cout << "After Deleting index 3: ";
[Link]();
}
Output:
Q2) Write a program using C++ to implement a fixed length Stack data
structure with push and pop operation.
Code:
#include <iostream>
using namespace std;
template <class T>
class Stack {
T arr[20];
int top;
public:
Stack() { top = -1; }
void push(T x) {
if (top == 19) {
cout << "Stack Overflow\n";
return;
}
arr[++top] = x;
}
T pop() {
if (top == -1) {
cout << "Stack Underflow\n";
return -1;
}
return arr[top--];
}
void display() {
for (int i = 0; i <= top; i++)
cout << arr[i] << " ";
cout << endl;
}
};
int main() {
Stack<int> s;
[Link](10);
[Link](20);
[Link](30);
cout << "Stack: ";
[Link]();
cout << "Popped: " << [Link]() << endl;
cout << "Stack now: ";
[Link]();
}
Output:
Q3) Write a program using C++ to implement Bubble sort.
Code:
#include <iostream>
using namespace std;
template <class T>
class Sorter {
public:
void bubbleSort(T 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])
swap(arr[j], arr[j + 1]);
}
void display(T arr[], int n) {
for (int i = 0; i < n; i++) cout << arr[i] << " ";
cout << endl;
}
};
int main() {
Sorter<int> s;
int arr[5] = {40, 20, 10, 50, 30};
cout << "Before Sort: ";
[Link](arr, 5);
[Link](arr, 5);
cout << "After Sort: ";
[Link](arr, 5);
}
Output:
Q4) Write a program using C++ to implement Binary search.
Code:
#include <iostream>
using namespace std;
template <class T>
class Search {
public:
int binarySearch(T arr[], int n, T key) {
int low = 0, high = n - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == key) return mid;
if (arr[mid] < key) low = mid + 1;
else high = mid - 1;
}
return -1;
}
};
int main() {
Search<int> obj;
int arr[5] = {10, 20, 30, 40, 50};
int key = 30;
int pos = [Link](arr, 5, key);
if (pos != -1)
cout << "Found at index " << pos;
else
cout << "Not Found";
}
Output: