4.1.1 Linear Data Structures
4.1.1 Linear Data Structures
4.1.1.1 Arrays: Ordered Boxes for Your Data
Imagine a row of numbered mailboxes, where each mailbox can hold one piece of information. That's a lot like an array! An array is a way to store a list of items in a specific order. Each item has a number (called an "index") that tells you where it is in the list, starting from 0.
For example, if you have an array of your favorite fruits: [ "Apple", "Banana", "Cherry", "Date" ]
- "Apple" is at index 0.
- "Banana" is at index 1.
- And so on!
Arrays are great because if you know the index, you can find any item super fast!
Fixed-size Arrays
Think of a bookshelf that has exactly 10 shelves. You can only put 10 books on it. A fixed-size array is like that bookshelf. When you create it, you tell the computer exactly how many items it can hold, and that number can't change later. If you want to add more items than there are spaces, you'd have to get a whole new, bigger bookshelf and move everything over!
- Example: A list of the days of the week will always have 7 days, so a fixed-size array could work well.
Dynamic Arrays
Now, imagine a shopping list that you can keep adding items to, even if you didn't know how many items you'd buy at the start. A dynamic array is like that flexible shopping list. It can grow or shrink as you add or remove items.
When a dynamic array gets full, the computer secretly makes a bigger one behind the scenes and moves all your items to the new, larger space. This makes it much easier for you to use, because you don't have to worry about running out of space!
- Example: A list of comments on a blog post, where new comments are always being added, would be a good fit for a dynamic array.
Bibliography for Arrays
- Kodable: Array Variables Teacher Overview
- Rebus Press: Fixed and Dynamic Arrays – Programming Fundamentals
- Brilliant Math & Science Wiki: Dynamic Array