11 + 12 + 13. Arrays Flashcards
array
collection of data items of the sametype
eg. array of 5 names
arrays are ordered
- there is an order to slots in an array
- each slot is numbered
- in C++ slots numbered from 0 upwards
need for arrays
- allows to store lots of values at one time
- can print in order of slots
declaring arrays syntax
data_type array_name[size];
must put declared size in the square brackets
explain this array:
double grades[6];
declares an array
- called grades
- that can hold up to 6 values
- of type value
the slots in this array are are numbered 0 to 5
declaring arrays - size of array
size of array must be known
can’t do this:
int size;
cin»_space; size;
int array[siz];
accessing array elements
in array[x], x is the subscript/index
how to access array elements examples
cin»_space; grades[1]
-reads in a value for slot 1
x = grades[i]
-gets value of the slot numbered by whatever value i currently has and ssigns it to x
array index expressions
index can be any expression whose value is an integer between 0 and (arraysize - 1)
eg. grades[i+2]
For loops and arrays
use for loops for handling all elements of an array
for loops and arrays syntax
for (i = 0; i
note on for loop condition
use arraysize in the FOR conditions rather than writing the number
index out of range errors
-occur in trying to access an array element beyond the end of the array
what will happen?
double grades[6];
grades [7] = 78;
will overwrite memory locations storing some other variable
what will happen?
double grades[6];
for (i = 1; i <=6; i++)
…
possibly disastrous