Week 5: Dynamic Arrays
Slide 1: Title Slide
o Content: "Dynamic Arrays"
o Subtitle: How to manage dynamic memory in C++.
Slide 2: What are Dynamic Arrays?
o Definition: Dynamic arrays can change size during runtime, unlike static arrays
that have a fixed size.
o Example: Dynamically adding elements when their number isn’t known at
compile-time.
cpp
Copy code
int n;
std::cout << "Enter the size of the array: ";
std::cin >> n;
int* arr = new int[n];
Slide 3: Creating Dynamic Arrays in C++
o Code: Creating a dynamic array using the new keyword:
cpp
Copy code
int* arr = new int[5]; // Allocates memory for 5 integers
for (int i = 0; i < 5; i++) {
arr[i] = i + 1;
std::cout << arr[i] << " ";
}
delete[] arr; // Releases allocated memory
o Explanation: The new operator allocates memory at runtime. It’s essential to
release memory using delete[] to avoid memory leaks.
Slide 4: Benefits of Using Dynamic Arrays
o Content: Dynamic arrays are flexible, can grow or shrink in size, and use memory
efficiently.
o Example: Resizing an array to accommodate more elements when the number of
elements exceeds initial size.
Slide 5: Example of Dynamic Array Usage
o Code: Program to input values into a dynamic array:
cpp
Copy code
int n;
std::cout << "Enter the number of elements: ";
std::cin >> n;
int* arr = new int[n];
for (int i = 0; i < n; i++) {
std::cout << "Enter element " << i + 1 << ": ";
std::cin >> arr[i];
}
std::cout << "Array contents: ";
for (int i = 0; i < n; i++) {
std::cout << arr[i] << " ";
}
delete[] arr; // Releases memory
Slide 6: Real-world Application
o Content: Dynamic arrays are crucial in applications like databases where data
storage requirements vary.
o Example: User data storage in web applications, where dynamic arrays adjust to
the amount of data saved.