Session 5 - Understanding Arrays

Objective: To understand how to use arrays and being able to traverse them with For/While loops. To also be able to add elements into an array.

An array is a data structure in C which allows us to store a group of related data values which are of the same data type. In this course, we will be looking at 1D and 2D arrays.

You can think of an array is a table. A 1D Array is a table of 1 column and multiple rows. A 2D Array is a table of multiple columns and multiple rows. We will look into 2D Arrays in the next session, where we implement a linked list!

What an Array looks like?

Below is the syntax for declaring and initialising a 1D Array: The Array's name is called ‘myArray’ which holds 5 values. Each value corresponds to an Index also known as its position. The type of the array here is ‘int’, so it can only hold integer values. Make sure to put square brackets after the array’s name!

Different types of Arrays and what They Hold.

Below is an example of the different types of arrays. We have a character array, holding letters, a ‘double’ array which is holding decimal numbers.

How to print the values from an Array.

In order to print the values of an array we must first access the position(index) of the value. Here we can see that when we compile the following program we get the following result.

What is happening we access the first position which starts at zero and prints it, and does the same for the rest.

Declaring an Array of a given length and giving each index a value.

Traversing an Array with a for loop.

Question:

Hugo has stored his product information in an one-d array. This does not include his prices. He wants to expand this into a two-d array. Because of the high increase in demand Hugo wants to increase his prices by 50%. iterate through the 2d array and make these changes.