Understand the use of arrays
📚 Programming: Understanding Arrays
What is an Array?
Think of an array as a row of lockers in a school hallway. Each locker has a unique number (its index) and can hold one item. In programming, an array stores a list of values, all of the same type, in a single variable. The first locker is index 0, the second is 1, and so on.
Example: int scores[5] = {85, 92, 78, 90, 88};
scores[0] = 85scores[1] = 92- …
scores[4] = 88
Key Array Concepts
- Size – The number of elements the array can hold. It is fixed after declaration.
- Indexing – Starts at
0and ends atsize-1. - Data type – All elements must be of the same type (e.g.,
int,char,double). - Accessing elements – Use
array[index]to read or write.
Array Example in Action
| Index | Value |
|---|---|
| 0 | 85 |
| 1 | 92 |
| 2 | 78 |
| 3 | 90 |
| 4 | 88 |
Common Array Operations
- Iteration – Loop through each element:
for (int i = 0; i < size; i++) { … } - Search – Find a value:
if (array[i] == target) { … } - Sorting – Arrange elements in order (e.g.,
Arrays.sort(array);). - Summation – Add all elements:
sum += array[i];
Exam Tip Box 🚀
1️⃣ Remember the index starts at 0.
2️⃣ Check array bounds. Accessing array[size] will cause an error.
3️⃣ Use loops wisely. A for loop is often the simplest way to process all elements.
4️⃣ Practice array manipulation. Write small programs that sort, reverse, or find the maximum value.
5️⃣ Show your work. In written answers, illustrate the array before and after each operation.
Revision
Log in to practice.