Data Stuctures and Algorithm Assignment 1
Data Stuctures and Algorithm Assignment 1
ASSIGNMENT 1
program should:
SOLUTION:
CODE:
#include <iostream>
using namespace std;
int main() {
int size;
cout << "Enter the size of the array: ";
cin >> size;
int* arr = new int[size];
cout << "Enter " << size << " integers:" << endl;
for (int i = 0; i < size; i++) {
cout << "Element " << i + 1 << ": ";
cin >> arr[i];
}
delete[] arr;
return 0;
}
OUTPUT:
Q2: Resizing a Dynamic Array
o Take a pointer to the dynamic array and its current size as inputs.
o Copy the contents of the old array into the new array.
SOLUTION:
CODE:
#include <iostream>
using namespace std;
int main() {
int size;
cout << "Enter the initial size of the array: ";
cin >> size;
if (size <= 0) {
cerr << "Error: Size must be greater than 0." << endl;
return 1;
}
cout << "Enter " << size << " integers:" << endl;
for (int i = 0; i < size; i++) {
cin >> arr[i];
}
ResizeArray(arr, size);
cout << "Array resized. New size: " << size << endl;
cout << "Contents of the resized array:" << endl;
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
delete[] arr;
return 0;
}
OUTPUT:
Q3: Dynamic Array-Based Stack
o Dynamically resize the array when the stack is full (double its size).
SOLUTION:
CODE:
#include <iostream>
using namespace std;
class Stack {
private:
int* arr;
int capacity;
int top;
void resize() {
int newCapacity = capacity * 2;
int* newArr = new int[newCapacity];
for (int i = 0; i < capacity; i++) {
newArr[i] = arr[i];
}
delete[] arr;
arr = newArr;
capacity = newCapacity;
}
public:
Stack(int size = 10) {
capacity = size;
arr = new int[capacity];
top = -1;
}
~Stack() {
delete[] arr;
}
int pop() {
if (isEmpty()) {
cerr << "Error: Stack underflow." << endl;
return -1;
}
return arr[top--];
}
int main() {
Stack stack;
stack.push(10);
stack.push(20);
stack.push(30);
cout << "Stack after pushing 10, 20, 30:" << endl;
stack.printStack();
stack.push(40);
stack.push(50);
return 0;
}
OUTPUT: