Sarwar Morshed American International University-Bangladesh (AIUB)
Sarwar Morshed American International University-Bangladesh (AIUB)
1
Arrays
Structures of related data items
Static entity (same size throughout program)
A few types
Pointer-based arrays (C-like)
Arrays as objects (C++)
2
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
3
Array elements like other variables
Assignment, printing for an integer array c
c[ 0 ] = 3;
cout << c[ 0 ];
Can perform operations inside subscript
c[ 5 – 2 ] same as c[3]
4
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
5
When declaring arrays, specify
Name
Type of array
Any data type
Number of elements
type arrayName[ arraySize ];
int c[ 10 ]; // array of 10 integers
float d[ 3284 ]; // array of 3284 floats
6
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
7
8