4.1 Array
4.1 Array
Arrays
Arrays
An array is a collection of data elements that are of the
same type (e.g., a collection of integers, collection of
characters, collection of doubles).
Arrays
1-dimensional array.
Array Applications
Given a list of test scores, determine the
maximum and minimum scores.
Read in a list of student names and rearrange
them in alphabetical order (sorting).
Given the height measurements of students in a
class, output the names of those students who
are taller than average.
Array Declaration
Syntax:
<data type> <arrayName>[<array_size>]
Ex. int Ar[10];
The array elements are all values of the type <data type>
The size of the array is indicated by <array_size>, the
number of elements in the array.
<array_size> must be an int constant or a constant
expression. Note that an array can have multiple dimensions.
Array Declaration
// array of 10 uninitialized ints
int Ar[10];
Ar
--
--
--
--
--
--
--
--
--
--
Subscripting
Declare an array of 10 integers:
int Ar[10];
// array of 10 ints
Last element has an index one less than the size of the array.
Ar[9]
Subscripting
// array of 10 uninitialized ints
int Ar[10];
--
Ar[3] = 1;
int x = Ar[3];
1
--
0
Ar
---
--
---1
------Ar[0] Ar[1] Ar[2] Ar[3] Ar[4] Ar[5] Ar[6] Ar[7] Ar[8]Ar[9]
Subscripting Example 1
//For loop to fill & print a 10-int array
#include <iostream>
using namespace std;
int main ( ) {
int index, ar[10]; // array for 10 integers
// Read in 10 elements.
cout << "Enter 10 integers: ";
for(index = 0; index < 10; index ++)
cin >> ar[index];
cout << endl;
cout << "The integers are ";
for(index = 0; index < 10; index ++)
cout << ar[index] << " ";
cout << endl;
return 0;
}
1
-8
6
3
--5
12
-Ar[0] Ar[1] Ar[2] Ar[3] Ar[4] Ar[5] Ar[6] Ar[7] Ar[8]Ar[9]
Ar[3] = -1;
-1
6
0
Ar
1
8
2
7
3
-1
4
5
5
4
6
3
7
2
8
1
9
0
11
10
Printing arrays
To print an array, you have to print each element in the array using a
loop like the following:
for (int i = 0; i < ARRAY_SIZE; i++)
{
cout << myList[i] << " ";
}
----
----
----
----
----
----
----
----
----
----
table
0
1
2
----
----
-a
--
----
----
----
table
0
1
2
a
g
m
b
h
n
c
i
o
d
j
p
e
k
q
f
l
r
table
0
1
2
t
m
n
w
e
a
o
n
l
d
i
a
i
o
r
table
0
1
2
t
m
n
w
e
a
o
n
l
d
i
a
i
o
r