Array
Array
Arrays
Arrays
Arrays
1-dimensional array.
Oct 14
Oct 15
Oct 16
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:
<type> <arrayName>[<array_size>]
Ex. int Ar[10];
The array elements are all values of the type <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];
0
Ar
Subscripting
// 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];
0
Ar
--
--
--
--
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;
}
Consider
int Ar[10], i = 7, j = 2, k = 4;
Ar[0] = 1;
Ar[i] = 5;
Ar[j] = Ar[i] + 3;
Ar[j+1] = Ar[i] + Ar[0];
Ar[Ar[j]] = 12;
cin >> Ar[k]; // where the next input value is 3
0
Ar
8
6
3
5
12
Ar[3] = -1;
-1
Ar
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] << " ";
}
Copying Arrays
Can you copy array using a syntax like this?
list = myList;
This is not allowed in C++. You have to copy individual
elements from one array to the other as follows:
for (int i = 0; i < ARRAY_SIZE; i++)
{
list[i] = myList[i];
}
Shifting Elements
double temp = myList[0]; // Retain the first element
// Shift elements left
for (int i = 1; i < myList.length; i++)
{
myList[i - 1] = myList[i];
}
// Move the first element to fill in the last position
myList[myList.length - 1] = temp;