Skip to content

Calculating indexes

Accessing the values in an array directly still requires you to access and process each value individually. So, where is the value in using an array? The key is in the array index. This is a numeric value that can be calculated rather than directly coded.

Watch the following video to see how to use expressions to calculate the index used to access each element of the array. See how you can use a loop to reduce the code needed to process your array, taking the same amount of code regardless of the number of elements in it.

Have a go at converting the code you have to make use of loops to interact with all elements of the array. Try doing this with a while loop and a for loop.

  • #include "splashkit.h"
    string read_string(string prompt)
    {
    string result;
    write(prompt);
    result = read_line();
    return result;
    }
    int read_integer(string prompt)
    {
    string line;
    line = read_string(prompt);
    return convert_to_integer(line);
    }
    int main()
    {
    // Declare a constant for the size of the array
    const int SIZE = 3;
    // Declare an array of three strings
    // The array is called names
    string names[SIZE];
    // Create a variable to store the index of the array
    // This can be used to control the loops below
    int i;
    // Assign values to the elements within the array
    // Start i at the first index - index 0
    i = 0;
    while ( i < SIZE ) // loop while i is less than the number of elements
    {
    // Store in the i-th element of the array
    // i changes each loop - so this will store in names[0], names[1], ...
    names[i] = read_string("Enter a name: ");
    i = i + 1; // increment i... could be written as i++
    }
    // Access elements in the array to write out names entered
    // Use a for loop to combine the loop control
    // - i is initialised to 0
    // - the loop continues while i is less than SIZE
    // - i is incremented each loop (at the end)
    for(i = 0; i < SIZE; i++)
    {
    write_line(names[i]);
    }
    return 0;
    }