6 - Arrays
6 - Arrays
ARRAYS
Objectives
2
General syntax:
The statement:
int list[10] = {0};
Declares an array of 10 components and initializes all
of them to zero
The statement:
int list[10] = {8, 5, 12};
Declares an array of 10 components and initializes
list[0] to 8, list[1] to 5, list[2] to 12
All other components are initialized to 0
Some Restrictions on Array Processing
14
Solution:
Other Ways to Declare Arrays
15
• Examples:
Searching an Array for a Specific Item
16
Example:
char name[16];
Since C-strings are null terminated and name has
16 components, the largest string it can store has
15 characters
If you store a string whose length is less than the
array size, the last components are unused
Character Arrays (cont’d.)
23
Examples:
To initialize row number 4 (fifth row) to 0:
Examples:
To input into row number 4 (fifth row):
Example:
To find the sum of row number 4:
Sum by Column
35
Example:
To find the sum of each individual column:
Largest Element in Each Row
36
• Example:
– To find the largest element in each row:
int matrix[noOfRows][NUMBER_OF_COLUMNS];
int largest;
//Largest element in each row
for (int row = 0; row < noOfRows; row++)
{
largest = matrix[row][0]; //Assume that the first element is the largest.
for (int col = 1; col < NUMBER_OF_COLUMNS; col++)
if (largest < matrix[row][col])
largest = matrix[row][col];
cout << "The largest element of row " << (row + 1) << " = " << largest <<
endl;
}
Multidimensional Arrays
37
To access a component:
Summary
38