18 Array
18 Array
Attique Ur Rehman
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.
0 1 2 3 4 5 6 7 8 9
Ar -- -- -- -- -- -- -- -- -- --
0 1 2 3 4 5
Subscripting
Declare an array of 10 integers:
int Ar[10]; // array of 10 ints
To access an individual element we must apply a
subscript to array named Ar.
A subscript is a bracketed expression.
– The expression in the brackets is known as the index.
First element of array has index 0.
Ar[0]
Second element of array has index 1, and so on.
Ar[1], Ar[2], Ar[3],…
Last element has an index one less than the size of the array.
Ar[9]
Incorrect indexing is a common error.
Subscripting
// array of 10 uninitialized ints
int Ar[10];
--
Ar[3] = 1;
int x = Ar[3]; 1 --
-- -- --
0 1 2 3 4 5 6 7 8 9
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;
}
Sorting with Arrays: Ex. 2
// Compare and sort three integers
void swap (int&, int&);
int main ( ) {
int ar[3]; // input integers
// Read in three elements.
cout << "Enter three integers: ";
cin >> ar[0] >> ar[1] >> ar[2];
if (ar[0] > ar[1]) swap (ar[0], ar[1]);
if (ar[1] > ar[2]) swap (ar[1], ar[2]);
if (ar[0] > ar[1]) swap (ar[0], ar[1]);
cout << "The sorted integers are " << ar[0]
<<", " << ar[1] << ", " << ar[2]
<< endl;
return 0;
}
Swapping Function: Ex. 2
// Function for swapping two integers
void swap (int& first, int& second) {
int temp;
temp = first;
first = second;
second = temp;
}
Array Element Manipulation Ex. 3
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 1 2 3 4 5 6 7 8 9
Ar 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]
Array Initialization Ex. 4
int Ar[10] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
0 1 2 3 4 5 6 7 8 9
Ar 9 8 7 6 5 4 3 2 1 0
Ar[3] = -1;
6 -1
0 1 2 3 4 5 6 7 8 9
Ar 9 8 7 -1 5 4 3 2 1 0
Initializing arrays with random
values
The following loop initializes the array myList with random
values between 0 and 99:
double total = 0;
for (int i = 0; i < ARRAY_SIZE; i++)
{
total += myList[i];
}
Finding the Largest Element