Professional Documents
Culture Documents
Prog6 Arrays
Prog6 Arrays
Objectives
General Objective
To use one dimensional and
multidimensional array variables
Specific Objectives:
To
declare them
Arrays Arrays
Arrays are used when you are dealing with
several related variables of the same type. You may decide to have
E.g. say you want
10 different variables to represent
to write a program that will let the user the 10 different integers,
enter 10 integers e.g. 2 4 6 8 …
10 scanf statements to have the
and then print them out in the reverse user enter values for them, and then
order that they were entered i.e. … 8 6 4
2… 10 printf statements to print them
How will you do this? out in reverse order.
1
11/9/2022
Arrays
Arrays A diagrammatic representation
Arrays
Arrays
An array is an identifier that refers to a
collection of data items that all have thesame
name. I T E M S
The data items must be of thesame type (e.g.
all integers or all characters). 0 1 2 3 4
you CANNOT store multiple types of data in
an array. A representation of an array with 5
Note that: an array is a fixed number of data
items.
character elements
Once you create it you cannot change its size.
2
11/9/2022
Arrays Arrays
Declaring Them Declaring Them
To declare an array, you must
specify 3 things: char arr_names[5];
the array type This declares an array of5
elements of type char.
the array name (identifier)
the array size (number of Th e n a m e o f t h e a r r a y i s
values you will store). arr_names.
Arrays Arrays
Declaring Them Accessing the Values
We now know an array is a
collection of data items that all
arr_names (Array name / identifier)
have the same name and type.
How can we distinguish the
individual array elements from one
<=5 characters shall be stored here
another?
By using the value that is assigned
to a subscript.
3
11/9/2022
Arrays Arrays
Accessing Their Elements Accessing the Values
(Array name / We use the following array syntax:
arr_names identifier)
array_name[i]
Elements
In C, array elements start at position (index) 0.
[0] [1] [2] [3] [4] Indices /
subscript Square brackets are used to access eachindexed
value (aka element).
Each element can be accessed by a combination of
Thus:
the array’s name and its position in the array
(subscript/index). arr_student_age[5]
BEWARE the off-by-one error; we start from index refers to the sixth element in an array called
0 (not 1). arr_student_age.
Arrays Arrays
Accessing Their Elements Accessing Their Elements
The name of the array is The first element of the array has index 0.
4
11/9/2022
Arrays
Accessing Array Elements
Accessing Their Elements
numbers
NOTE:
The value inside of the brackets does not
have to be a constant.
To access numbers’ first element:
It could be a variable or expression.
numbers[0] E.g.:
numbers[9]
or even
numbers[mark * 2 + 1]
Arrays Arrays
Assigning Values Assigning Values
int marks [5]; //var declaration
marks We have created an array calledmarks
marks[0] = 21;
21 28 8 16 0 marks has space for 5 int variables.
marks[1] = 28; [0] [1] [2] [3] [4] We then assign integer values to the variables.
Notice that we stored 0 in the last space of
marks[2] = 8; the array.
5
11/9/2022
Arrays Arrays
Assigning Values Assigning Values
Arrays Arrays
Assigning Values Declaring Them
Assigning values to array elements: Arrays may consist of any of
numbers[8] = mark; the valid data types.
Arrays are declared along
Assigning array elements to a
variable: with all other variables in the
declaration section of the
mark = numbers [9]; program …
6
11/9/2022
int main()
void main()
{
{ // Declare an array to store the ages (in years) of five children
int ageArray[5];
int numbers[100]; <— Xcode warning: Unused //Enter the values of the elements of the array
float averages[20];
ageArray[0]=10;
variable ‘averages' ageArray[1]=11;
numbers[2] = 10; ageArray[2]=9;
ageArray[3]=8;
--numbers[2]; ageArray[4]=12;
Output Arrays
Processing Them
The first child's age is 10 years.
The second child's age is 11 years. C does NOT allow single operations involving
The third child's age is 9 years. entire arrays.
The fourth child's age is 8 years.
The fifth child's age is 12 years. Any operations must be carried out on an
Program ended with exit code: 36 element by elementbasis.
Note: Examples of operations:
The exit code is not 0 as the compiler
assignment
warned us that:
comparison
Return type of ‘main’ is not ‘int’
7
11/9/2022
Arrays Arrays
Assigning Values
Processing Them
For instance, it is NOT acceptable to assign one
array to another array even if they are similar:
Instead, you have to copy one element (value)
i.e. even if they have the same data type, at a time.
same dimensionality and same size.
Thus, any such operations must be carried out
Let numbers and elements be arrays of 10 on an element by element basis
.
integers each.
We usually accomplish this within aloop.
It is NOT possible to say:
Each pass through the loop is used to process
elements = numbers; one array element.
Arrays Arrays
Processing Them Processing Them
for (i = 0; i < 10; ++i)
We usually use for loops to {
iterate over an array when printf("The number is: %d",
numbers[i]);
accessing its elements or }
writing data to those The condition takes into account
elements. the fact that the numbers array
has 10 elements.
8
11/9/2022
9
11/9/2022
Arrays Arrays
Accessing Their Elements – The Accessing Their Elements – The Example Explained
Example Explained
Arrays Arrays
Accessing Their Elements – The Example Explained Accessing Their Elements – The Example Explained
10
11/9/2022
Arrays
Accessing Their Elements – The Example Explained Arrays
Accessing Their Elements – The Example
If you wrote: Explained
for (num1 = SIZE - 1; num1 >= 0; num1--) You need two extra
printf(“%d, ", numbers[num1]);
statements to ensure:
It would print out:
no comma is printed out
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, Program
before the first element to
ended with exit code: 0 be printed or after the last,
and
There would be a comma at the end of only one newline is printed
the list of numbers. out at the end.
Arrays Arrays
Accessing Their Elements – The Example Explained Accessing Their Elements – The Example Explained
11
11/9/2022
Arrays Arrays
Accessing Their Elements – The Example Explained
Accessing Their Elements – A
printf("%d", numbers[SIZE - 1]);
2nd Example:
for (num1 = SIZE - 2; num1 >= 0; num1--)
printf(", %d", numbers[num1]);
printf("\n"); The following programme
In this for loop, notice that unlike our first version of this
reads in text one character at
program, we are now starting num1 at a time until an EOF is read
SIZE - 2 and keeps track of how many
instead of
times each digit (0 through
SIZE - 1 9) is encountered.
Why?
We’ve already printed out thearray’s last element.
#include <stdio.h>
Arrays
Accessing Their Elements – A
Arrays
int main(void)
{
2nd Example: Initialising Values
char c;
int arr_digits[10];
int x;
We have to initialise all the values in the array.
for (x = 0; x <= 9; x++) Just like with simple variables, if the array
arr_digits[x] =0;
values are not initialised, they are
while ((c = getchar()) != EOF)
{ unpredictable.
if ((c >= '0') && (c <= '9'))
Why do we have to initialise the array here but
++arr_digits[c -'0'];
} not in the first program?
for (x = 0; x <= 9; x++) Because in the first program, we have the
printf("%d\n", arr_digits[x]);
return 0;
user enter all the values, and these values are
} assigned directly to the array.
Output:
12
11/9/2022
Arrays Arrays
Initialising Values Assigning Values
Arrays Arrays
Accessing Their Elements – A 2
nd
Assigning Values Example Explained:
Remember, it is NOT acceptable to In the example2 prog, when we read a digit, we can
assign one array to another array. check if the character 'c' represents a digit by
checking if it is greater than or equal to thecharacter
Let numbers and elements be '0' and less than or equal to thecharacter '9'.
arrays of 10 integers each. This is because the ASCII codes for the digits
0,1,2,…,9 are 48 through 57 respectively.
It is NOT possible to say: It is for this reason also that we can subtract the
elements = numbers; character '0' from the character 'c' to find the
appropriate index in the array.
Instead, you have to copy one Characters used in expressions are treated as their
ASCII values, so '0' - '0' = 0, '1' - '0' = 1, etc.
element (value) at a time.
13
11/9/2022
A Grading Program
14
11/9/2022
Arrays
Arrays
Initialising Values
What does the following code snippet do?
Just like with simple variables, if the
array values are not initialised, they are
unpredictable.
int arr_digits[10], i; Why do we have to initialise the array
for (i = 0; i <= 9; i++) here but not in the example program (the
arr_digits[i] =0; one reversing numbers)?
Because in the first program, we have
It initialises all the values in the array the user enter all the values, and these
to zero. values are assigned directly to the array.
Arrays Arrays
Simultaneous Declaration & Initialisation
Simultaneous Declaration &
Initialisation
#include <stdio.h>
int main()
In C, it is also possible toinitialise an array as it is
declared.
{
int values[] = { 1,2,3,4,5,6,7,8,9 };
int numbers[10] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; char word[5] = { 'H','e','l','l','o' };
Specify the starting values of the array within curly printf("%s \n", word);
braces. }
i.e. the initial values are enclosed in braces.
Separate them with commas. Output? Xcode warning: Unused variable 'values'
Hello
Program ended with exit code: 0
15
11/9/2022
Arrays
Simultaneous Declaration &
Initialisation
Multidimensional Multidimensional
Arrays Arrays
The arrays we’ve covered so far are all
linear (one dimensional).
0 1 2 …. n
Think of one-dimensional arrays as a
single sequence of values. 1
We can also declare multidimensional 2
arrays …
For instance, 2D arrays are often used n
to represent grids, game boards, tables,
etc.
16
11/9/2022
Multidimensional Multidimensional
Arrays Arrays
Multi-dimensioned arrays have two or int myArray [10][10];
more index values which specify the Declares an array matrix that is a 2D
0 1 2 …. 9
element in the array. array with 10 rows and 10 columns for 1
a total of 100 elements.
multi[i][j] By convention, 2
In this example, the first dimension (index/subscript) is …
used to represent the rows, numbered
the first index value i specifies a row top to bottom starting at 0, and 9
index, whilst the second dimension (index/subscript)
is used to represent the columns,
numbered left to right starting at 0.
j specifies a column index.
17
11/9/2022
18
11/9/2022
Multidimensional Arrays
Initialising as you Declare Them
00 01 02 Task: Write
Class Exercise
10 11 12 code to print
Multidimensional Arrays
20 21 22 this table on
30 31 32 your screen
exactly as is.
40 41 42
Multidimensional Arrays
Initialising as you Declare Them
Note
To C, 00, 01, and 02 are equivalent to 0,
1, and 2.
Multidimensional Arrays
These are the values that are stored, and
when you print the numbers out, you Some Practical Applications
won't see the 0 in the 10's column
Hint:
Use the 0 flag and a width of 2 in your
printf statement.
19
11/9/2022
20
11/9/2022
Prac App 2
21
11/9/2022
Prac App 2
Board Games
22
11/9/2022
Possible values for each slot in the board might be Of course, if you prefer,
'r' for a normal red checker, you could also use an
integer array, and use
'R' for a red king, specific integers to
'b' for a normal black checker, represent the different
types of possible pieces.
'B' for a black king,
and some other default value to represent empty
spaces.
23
11/9/2022
Multidimensional
Multidimensional Arrays
Arrays
It is possible to have arrays with more than
2D arrays can also be used for two dimensions.
representing structures such as You can have three-dimensional arrays, four-
spreadsheets. dimensional arrays, etc.
They are also commonly used Practical Example of a 3D array:
in platform video games (e.g. A 5 storey parking area with many slots on
Super Mario) to represent each floor for cars.
terrain or screen. To locate a car you’d need the floor number
along with the row & column number at
that floor.
Multidimensional Arrays
Multidimensional Arrays
Visualise a:
1D array as a row of data
2D array as a table of data/matrix/spreadsheet
3D array as a stack of tables
We use
3 nested loops to process 3D arrays
4 nested loops to process 4D arrays
Etc
24
11/9/2022
Multidimensional
Arrays
25
11/9/2022
26
11/9/2022
So the formula takes the starting address of the array and adds the The address of the 2nd element in the 2nd row will be:
number of bytes which is the offset to the current element.
0 + (4) *(1 * 3 + 1) = 16
27
11/9/2022
Arrays
Accessing Out of Bounds Elements
Arrays Arrays
Accessing Out of Bounds Accessing Out of Bounds
Elements Elements
However,
if we are reading the value, it will be
unpredictable, and The “array is out of bounds” error is a
runtime error.
if we are assigning a value, we will be writing
to memory that isn't owned by this array. The compiler will not detect this error
It will cause an error sooner or later unless you
It has no idea you are assigning/accessing
are extremely lucky!
something greater than the array’s size.
Sometimes this type of bug is difficult to track
down.
28
11/9/2022
Arrays
Accessing Out of Bounds
Elements
An out of bounds error can:
cause your program to crash
cause your program to produce inconsistent
results (with garbage data that is meaningless
in the array).
It is up to you (the programmer),not the
compiler, to be super careful when
accessing the array index values in use and/or
writing data to the array with the index value.
29