Outline 7.2 Arrays 7.3 Declaring Arrays 7.4 Examples Using Arrays 7.5 Passing Arrays To Functions 7.9 Multidimensional Arrays
Outline 7.2 Arrays 7.3 Declaring Arrays 7.4 Examples Using Arrays 7.5 Passing Arrays To Functions 7.9 Multidimensional Arrays
Chapter 4 - Arrays
Outline
7.1 Introduction
7.2 Arrays
7.3 Declaring Arrays
7.4 Examples Using Arrays
7.5 Passing Arrays to Functions
7.9 Multidimensional Arrays
7.1 Introduction
• Arrays
– Structures of related data items
– Static entity (same size throughout program)
• A few types
– Pointer-based arrays (C-like)
– Arrays as objects (C++)
7.2 Arrays
• Array
– Consecutive group of memory locations
– Same name and type (int, char, etc.)
• To refer to an element
– Specify array name and position number (index)
– Format: arrayname[ position number ]
– First element at position 0
• N-element array c
c[ 0 ], c[ 1 ] … c[ n - 1 ]
– Nth element as position N-1
7.2 Arrays
7.2 Arrays
Name of array (Note
that all elements of
this array have the
same name, c)
c[0] -45
c[1] 6
c[2] 0
c[3] 72
c[4] 1543
c[5] -89
c[6] 0
c[7] 62
c[8] -3
c[9] 1
c[10] 6453
c[11] 78
• Initializing arrays
– For loop
• Set each element
– Initializer list
• Specify each element when array declared
int n[ 5 ] = { 1, 2, 3, 4, 5 };
• If not enough initializers, rightmost elements 0
• If too many syntax error
– To set every element to same value
int n[ 5 ] = { 0 };
– If array size omitted, initializers determine size
int n[] = { 1, 2, 3, 4, 5 };
• 5 initializers, therefore 5 element array
Element Value
fig04_03.cpp
0 0 (2 of 2)
1 0
2 0 fig04_03.cpp
3 0 output (1 of 1)
4 0
5 0
6 0
7 0
8 0
9 0
• Array size
– Can be specified with constant variable (const)
• const int size = 20;
– Constants cannot be changed
– Constants must be initialized when declared
– Also called named constants or read-only variables
Face Frequency
1 1003
2 1004
3 999
4 980
5 1013
6 1001
• Arrays passed-by-reference
– Functions can modify original array data
– Value of name of array is address of first element
• Function knows where the array is stored
• Can change original memory locations
• Individual array elements passed-by-value
– Like regular variables
– square( myArray[3] );
Unsorted array:
34 56 4 10 77 51 93 30 5 52
Sorted array:
4 5 10 30 34 51 52 56 77 93