Arrays
Arrays
Arrays
Array
Consecutive group of memory locations Same name and type (int, char, etc.) Static entity (same size throughout program) Index value is written inside a pair of square beackets []
Arrays
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 ]
Arrays
Array elements like other variables
Assignment, printing for an integer array c
c[ 0 ] = 3; cout << c[ 0 ];
Types
Arrays are usually divided in to two types
One Dimensional Two Dimensional
Introduction to Programming
Declaring Arrays
When declaring arrays, specify
Name Type of array
Any data type
Initializer list
Specify each element when array declared
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Initializing an array with a declaration. #include <iostream> #include <iomanip> using namespace std; void main() { // use initializer list to initialize array n int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
} // end main
Element 0 1 2 3 4 5 6 7 8 9
Value 32 27 64 18 95 14 90 70 60 37
Arrays
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
Arrays
#include <iostream> #include <iomanip> using namespace std; void main() { const int arraySize = 10; int s[ arraySize ]; // array s has 10 elements // set the values
for ( int j = 0; j < arraySize; j++ ) cout << Value at index << j << is << s[ j ] << endl; }
Arrays
Using const
void main() { const int x; x = 7;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
int total = 0;
// sum contents of array a for ( int i = 0; i < arraySize; i++ ) total += a[ i ];
cout << "Total of array element values is " << total << endl;
} // end main
String
Array of characters char test[6] = {h, e, l, l, o}; char test[6] = hello;
Introduction to Programming
Example Program
Write a program that prints array elements in reverse order.
#include<iostream.h> void main() { int abc[5], i; for (i=0;i<=4;i++)
Cin>>abc[i];
}
Introduction to Programming
Multi-dimensional Arrays
Very useful and practical, e.g.
Matrices Images int a[3][3] = { {1,2,3}, {4,5,6}, {7,8,9} };
Multiple loops to access individual elements
Introduction to Programming