0% found this document useful (0 votes)
12 views3 pages

mDSA Lab Task 9

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)
12 views3 pages

mDSA Lab Task 9

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/ 3

Lab Task 09

Data Structures & Algorithms


By

Syed Muzammil Ahmed


(3014-2022)
Program: BSCS - 4B

Course/Lab Instructor
Sir Maaz.

Faculty of Engineering Sciences and Technology


Hamdard University, Karachi, Pakistan
LAB TASK 09

Task 1:

Dynamic Array :

#include <iostream>
class DynamicArray
{ private:
int* array;
int capacity;
int size;

void resize(int newCapacity) {


int* newArray = new int[newCapacity];
for (int i = 0; i < size; ++i) {
newArray[i] = array[i];
} delete[]
array; array = newArray;
capacity = newCapacity;
}
public:
DynamicArray(int initialCapacity = 2) :
capacity(initialCapacity), size(0) {
array = new int[capacity];
}

~DynamicArray() {
delete[] array;
} void add(int element)
{ if (size == capacity) {
resize(capacity * 2);
}
array[size++] = element;
}
int get(int index) const { if
(index >= 0 && index < size) {
return array[index];
}
throw std::out_of_range("Index out of range");
}
void print() const {
for (int i = 0; i < size; ++i) {
std::cout << array[i] << " ";
}
std::cout << std::endl;
}

1
int getSize() const
{ return size;
}
};
int main() {
DynamicArray arr;
arr.add(10);
arr.add(20);
arr.add(30);
arr.add(40);

std::cout << "Array elements: ";


arr.print();

std::cout << "Element at index 2: " << arr.get(2) << std::endl;


std::cout << "Size of array: " << arr.getSize() << std::endl;

return 0;
}
Outputr:

You might also like