Jump to content

3.5.1 Arrays (One-dimensional, Multi-dimensional)

From Computer Science Knowledge Base

3.5.1 Arrays (One-dimensional, Multi-dimensional)

Imagine you have a row of mailboxes, all lined up. Each mailbox has a number (like 1, 2, 3...) and can hold one letter. If you want to find the letter in mailbox number 5, you just go directly to mailbox 5.

An Array is like a row of mailboxes (or a list of numbered slots) in a computer's memory. It's a data structure that stores a fixed-size collection of items of the same type in a specific order. Each item in the array has a special number called an index (starting from 0 for the first item).

  • Fixed-size: Once you create an array, you usually can't change how many items it can hold.
  • Same type: All items in an array must be of the same data type (e.g., all numbers, or all words).
  • Ordered: The items are stored in a specific order, and you can access them using their index.

Types of Arrays:

  • One-dimensional Arrays:
    • This is the simplest type, like a single row of mailboxes. It's a list of items.
    • Example: A list of student scores: [85, 92, 78, 95, 88]
      • Score at index 0 is 85
      • Score at index 1 is 92
      • ...and so on.
    • You would use a one-dimensional array to store a list of names, a list of temperatures, or a list of answers to a quiz.
  • Multi-dimensional Arrays:
    • Imagine a grid of mailboxes, like a checkerboard, or seats in a movie theater that have both a row number and a seat number.
    • A multi-dimensional array (most commonly a two-dimensional array) is an array of arrays. It's used to store data in a table-like format, with rows and columns.
    • Example: A chessboard (8 rows, 8 columns) or a seating chart for a classroom.
      • To find a specific seat, you'd need two numbers: row and column.
      • grades[row][column] might store the grade of a student in a specific seat.
    • You might use a two-dimensional array to store pixel data for an image, a game board, or a spreadsheet.

Arrays are fundamental for storing collections of similar data in an organized and quickly accessible way, especially when you know exactly how much data you'll be storing.

Bibliography: