Composite Variables
- This semester we have encountered a number of simple data types.
- integers, characters, floats.
- These are data types that are represented at the basic hardware level.
- They also contain only one value.
- While these are extremely useful, as you go along in programming it is convenient to group data together.
- These form what the book calls composite data types.
- For now, we will focus on two of these.
- An array is a homogeneous collection of items.
- Items in an array are called elements.
- Items are accessed by an index or number.
- The index normally runs between 0 and size-1, when the array holds size elements.
- This is because the index is an offset from the beginning of the array.
- We indicate the item with [].
- Consider the array Names.
-
Index | Data |
0 | Fred |
1 | Sue |
2 | Amanda |
3 | Bob |
4 | Lisa |
5 | Tim |
6 | Todd |
7 | Scott |
- What is at Names[0]
- What is at Names[6]
- What is the index of Lisa?
- How many elements are in the array?
- What is the largest index?
- When an index is below 0 or greater than or equal to the size, an error occurs.
- This is an array index out of bounds error.
- Why count from zero?
- Address of data = base address + index * size_of(elements)
- When we deal with arrays, we normally have three different data items
- The array
- The capacity of the array or the maximum number of items it can hold.
- The size of the array, or the actual number of items in the array.
- A record, sometimes called a structure
- This is a heterogeneous collection of data.
- Generally the data is called a field
- And fields are accessed by field name.
- Frequently fields are accessed by structure.field.
- Consider the structure Student
-
Field | Type | Value |
Name | string | Bob |
Age | int | 19 |
GPA | float | 2.81 |
- What is contained in Student.Age?
- What is contained in Student.GPA
- What do you think would happen if we executed
Student.name=Fred
- We use arrays when we have a bunch of the same thing.
- Think attendance roster, list of party guests, shopping list.
- We use structures when we want to group different types of data together.
- Think driver's license, student information, parts to a piece of furniture.