Menu
Theme
Bachelor of Science in Computer Science
Course Content

Arrays

Introduction to Programming (C/C++)

Sasa! Let's Talk About Arrays - The Programmer's Matatu!

Habari yako, future tech guru! Welcome to our class on Arrays. Imagine you're building an app to track your M-Pesa expenses for the week. You have an expense for Monday, Tuesday, Wednesday... all the way to Sunday. How would you store this in code? You could create seven different variables:


// The hard way...
float expenseMonday = 50.0;
float expenseTuesday = 120.50;
float expenseWednesday = 75.0;
// ...and so on. Hectic, right?

That's a lot of work! What if you needed to track expenses for a whole year? That would be 365 variables! Eeeh! There must be a better way. And there is! This is where our hero of the day, the Array, comes in to save us. Think of an array like an egg tray or a 14-seater matatu – a single container holding multiple items of the same kind, all neatly organized.

Image Suggestion: A vibrant, colourful digital illustration of a Kenyan matatu with 14 clearly numbered seats (0 to 13). Beside it, an egg tray with eggs, also numbered starting from 0. The style is modern and clean, with the title "Arrays: Organized Data!"

So, What Exactly is an Array? (Nini Hii Array?)

In programming, an array is a data structure that stores a collection of elements of the same data type in contiguous memory locations.

Let's break that down in a way that makes sense:

  • Same Data Type: Just like a matatu carries only people (passengers) and an egg tray carries only eggs, an array can only hold one type of data. It can be an array of integers (like KCSE scores), an array of floating-point numbers (like M-Pesa balances), or an array of characters (like the letters in your name). You can't mix them up in a single basic array!
  • Contiguous Memory Locations: This sounds complicated, but it just means the items are stored next to each other in the computer's memory, like seats in a matatu. Seat 1 is right next to Seat 2, which is next to Seat 3. This makes it very fast for the computer to access them.

Here’s a simple visual representation of an array that holds 5 integer values:


  An array named 'studentMarks' of size 5:

  +----+----+----+----+----+
  | 78 | 92 | 85 | 66 | 95 |  <-- The values (marks)
  +----+----+----+----+----+
    0    1    2    3    4     <-- The Index (seat number)

How to Declare an Array in C++ (The "Form Ni Gani?" Section)

Declaring an array is like telling the computer you need to book a matatu. You need to specify the type of passengers, give the matatu a name (number plate), and say how many seats you need.

The syntax is simple:


dataType arrayName[arraySize];

Let's declare an array to hold the KCSE scores of 10 students:


// We need to store 10 integers (the scores)
int kcseScores[10]; 
  • int is the data type. All our scores will be whole numbers.
  • kcseScores is the name we have given our array.
  • [10] is the size. We have reserved 10 spots in memory for our scores.

Accessing Array Elements: The Magic of the Index

Okay, so we have our matatu (the array). How do we talk to a specific passenger? We use their seat number! In arrays, this "seat number" is called an index.

IMPORTANT RULE: In C++ (and most programming languages), array indexing starts from ZERO (0). Hii ni muhimu sana! The first element is at index 0, the second at index 1, and so on. For our array of 10 scores, the valid indices are from 0 to 9.


  Array: kcseScores[10]

  Index 0: First student's score
  Index 1: Second student's score
  ...
  Index 9: Tenth student's score

To place a value in an array or to get a value from it, you use the array name followed by the index in square brackets [].


// Let's assign the first student a score of 410
kcseScores[0] = 410;

// Let's assign the third student a score of 398
// Remember, the third student is at index 2!
kcseScores[2] = 398;

// To print the first student's score:
cout << kcseScores[0]; // This will output 410
Real-World Scenario: Think of the 47 counties in Kenya. If we stored them in an array, we could have `string counties[47];`. To get the first county, we'd use `counties[0]` (which might be "Mombasa"), and the last one would be `counties[46]` (which might be "Nairobi"), not `counties[47]`! Forgetting that indexing starts at 0 is a very common mistake for new programmers.

Initializing an Array (Let's Fill The Seats!)

You can give your array values right when you create it. This is called initialization. Let's create an array to store the number of goals scored by Harambee Stars in their last 5 matches.


// Initialize the array at the time of declaration
int goalsScored[5] = {2, 1, 0, 3, 1};

// Now the array looks like this in memory:
// goalsScored[0] is 2
// goalsScored[1] is 1
// goalsScored[2] is 0
// goalsScored[3] is 3
// goalsScored[4] is 1

Let's Code! A Full C++ Example

Here is a simple program that creates an array of the populations of 4 major towns in Kenya, and then prints them out using a `for` loop. A loop and an array are best friends!


#include <iostream>
using namespace std;

int main() {
    // Declare and initialize an array to hold populations
    int townPopulation[4] = {4329000, 1521000, 928000, 894000};
    
    // Create a corresponding array for town names
    string townName[4] = {"Nairobi", "Mombasa", "Kisumu", "Nakuru"};

    cout << "Kenya Urban Population Data:" << endl;
    cout << "--------------------------" << endl;

    // A for loop is perfect for going through an array
    // We start at index 0 and go up to index 3
    for (int i = 0; i < 4; i++) {
        // We use 'i' as the index to access each element in turn
        cout << townName[i] << " has a population of: " << townPopulation[i] << endl;
    }

    return 0;
}

Expected Output:


Kenya Urban Population Data:
--------------------------
Nairobi has a population of: 4329000
Mombasa has a population of: 1521000
Kisumu has a population of: 928000
Nakuru has a population of: 894000

Arrays and Memory (A Quick Look Under the Hood)

When you declare `int kcseScores[10];`, the computer finds a block of memory big enough to hold 10 integers. In most modern systems, one `int` takes up 4 bytes of memory.

So, we can calculate the total memory our array will use:


Total Memory = arraySize * sizeof(dataType)

For our `kcseScores` array:


Total Memory = 10 * sizeof(int)
Total Memory = 10 * 4 bytes
Total Memory = 40 bytes

Because they are in contiguous memory, the computer knows exactly where to find each element. It takes the starting address of the array and just adds a little bit to find the element you asked for. That's why arrays are so fast!

Image Suggestion: A simplified diagram showing a computer memory lane (like a street). A block labeled "kcseScores Array" occupies a segment of the street. Inside the block are 10 smaller boxes labeled [0], [1], [2]...[9]. An arrow points to the start of the block with a label like "Base Address: 0x7FFF5FBFF620".

What's Next? Multi-dimensional Arrays

So far, we've only seen one-dimensional arrays, like a single row of seats in a matatu. But what if you have a parking lot full of matatus, arranged in rows and columns? That's a 2D Array!

You can think of it like a grid, a calendar, or a chessboard. It's an array of arrays.


  A 2D Array (3 rows, 4 columns)

      Col 0  Col 1  Col 2  Col 3
      +------+------+------+------+
Row 0 | [0][0]| [0][1]| [0][2]| [0][3]|
      +------+------+------+------+
Row 1 | [1][0]| [1][1]| [1][2]| [1][3]|
      +------+------+------+------+
Row 2 | [2][0]| [2][1]| [2][2]| [2][3]|
      +------+------+------+------+

We will cover these in more detail later, but just know that they exist and are incredibly useful for things like creating games, tables of data, and working with images.

Conclusion

Umeelewa? Sawa sawa! You've just learned one of the most fundamental and powerful tools in programming. Arrays are the backbone of how we handle large sets of data efficiently.

Let's recap the main points:

  • An array is a collection of elements of the same type.
  • Elements are stored next to each other in memory.
  • We use an index to access elements, and the index always starts at 0.
  • Arrays and loops work together perfectly to process data.

Keep practicing, and soon using arrays will feel as natural as catching a matatu to town. In our next lesson, we'll explore more powerful ways to use arrays with functions and start looking at strings, which are just a special kind of array! Kazi nzuri!

Pro Tip

Take your own short notes while going through the topics.

Previous Loops
KenyaEdu
Add KenyaEdu to Home Screen
For offline access and faster experience