Arrays fixed size Declared as type namesize Examples

  • Slides: 8
Download presentation
Arrays – fixed size • Declared as type name[size] • Examples: float x[10]; int

Arrays – fixed size • Declared as type name[size] • Examples: float x[10]; int arr[100]; • The size must be an integer • All array elements must have the same type

Array – variable size • Declared as type name[] • Examples: float x[]; int

Array – variable size • Declared as type name[] • Examples: float x[]; int arr[]; • The size is not always known • All array elements must have the same type

Arrays of fixed size -usage • Declared as any other variable type name[size] •

Arrays of fixed size -usage • Declared as any other variable type name[size] • Examples: float x[10]; int arr[100]; • Use them in variable declarations • Use them as arguments (or parameters) to functions

Two common ways to use arrays • To iterate through a set of elements

Two common ways to use arrays • To iterate through a set of elements in order • To accumulate information about a set of elements

Iterating through a set of elements • Start at the beginning • Usually with

Iterating through a set of elements • Start at the beginning • Usually with the counter set to 0 • Examine each array element as the counter increases • STOP when you reach the end of the array

Example of stopping at the end • int arr[100]; • i = 0; •

Example of stopping at the end • int arr[100]; • i = 0; • while (i < 100) printf(“%dn”, arr[i]); • The process stops when the 100 th element (the one with index 99) is reached. • The 1 st element in the array has index 0 !

Accumulating information int arr[100]; i = 0, sum = 0; while (i < 100)

Accumulating information int arr[100]; i = 0, sum = 0; while (i < 100) { sum += arr[i]; i++; } printf(“%dn”, sum); The process stops when the 100 th element (the one with index 99) is reached. The sum is added to as the iteration continues

One last reminder • Make sure you don’t go past the end of the

One last reminder • Make sure you don’t go past the end of the array – you know its size