Array CS Thinking Example 4
Follow the full solution, then compare it with the other examples linked below.
Example 4
mediumGiven `scores = [12, 15, 9, 20]`, what are `scores[0]` and `scores[3]`, and what happens if code tries to read `scores[4]`?
Solution
- 1 Step 1: Arrays usually start at index 0, so scores[0] = 12 and scores[3] = 20.
- 2 Step 2: There is no fifth element, so trying to read scores[4] would cause an out-of-bounds error or an invalid/undefined result depending on the language.
Answer
scores[0] = 12, scores[3] = 20, and scores[4] is out of bounds.
Arrays store multiple values using numbered positions. Understanding zero-based indexing and valid index ranges is essential to avoid common programming errors.
About Array
An ordered collection of values stored together under a single name and accessed by their numeric index position. Arrays allow you to store, retrieve, and manipulate multiple related values efficiently using loops and index-based access.
Learn more about Array โMore Array Examples
Example 1 easy
An array `scores` contains [85, 92, 78, 95, 88]. What is scores[0]? What is scores[3]? How many elem
Example 2 mediumWrite pseudocode to find the sum of all elements in an array `nums = [4, 7, 2, 9]`.
Example 3 mediumGiven array `names = ['Alice', 'Bob', 'Charlie']`, what is names[1]? What happens if you access name