Lecture 6
Lecture 6
Lecture 6
Lecture Outline
• Arrays
• Accessing array elements
• Processing Arrays
• Parallel Arrays
• Multidimensional Arrays
Introduction
• Arrays are used to store multiple values in a single variable,
instead of declaring separate variables for each value.
• Suppose a class has 30 students, and we need to store all their
grades. Instead of creating 30 separate variables, we can simply
create an array.
double grades[30];
• Here, the name of the array is grades. The array can hold a maximum
of 30 grades (double).
• The size and type of arrays cannot be changed after its
declaration.
Arrays
• An array simply refers to a collection of variables of the same
type and referenced by the same name.
• It is a series or list of values in computer memory, all of which have
the same name and data type but are differentiated with special
numbers called subscripts.
• For example, a shopping list may include: milk, bread, wheat,
rice, gari, flour, …
• A subscript, also called an index, is a number that indicates the
position of a particular item within an array.
How Arrays Occupy Computer Memory
• When an array is created, you declare a structure that contains
multiple data items but with the same name and same data
type
• Each item in an array is one element that occupies an
area/space in memory next to or contiguous the other.
• You indicate the number of items with the size of the array:
datatype array_name [ size ];
• To find out how many elements an array has, you have to divide the size
of the array by the size of the data type it contains:
int myNumbers [ 5 ] = {10, 20, 30, 40, 50};
int getArrayLength = sizeof( myNumbers ) / sizeof( int );
cout << getArrayLength;
Partial Array Initialization
• When an array is initialized, it is possible to initialize part of the array.
• Example: int x [ 10 ] = {20, 9, 16, 12};
array x [0] x [1] x [2] x [3] x [4] x [5] x [6] x [7] x [8] x [9]
Data 20 9 16 12
Index 0 1 2 3 4 5 6 7 8 9
int main() {
int test[3][2] = { {2, -5}, {4, 0}, {9, 1} };
for(int row = 0; row < 3; row++ ){
for (int col = 0; col < 2; col++) {
cout << "test[" << irow << "][" << col<< "] = " << test [ row ][ col ] << endl;
}
}
return 0;
}
Multi-dimensional Arrays
#include <iostream> cout << "The numbers are: " << endl;
using namespace std; for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
int main ( ) { cout << "numbers[" << i ;
int numbers [ 2 ] [ 3 ]; cout << "][" << j << "]: " ;
cout << "Enter 6 numbers: " << endl; cout << numbers [ i ] [ j ] << endl;
}
for (int i = 0; i < 2; ++i) { }
for (int j = 0; j < 3; ++j) { return 0;
cin >> numbers [ i ][ j ]; }
}
}