Problem Solving i Chapter 4
Problem Solving i Chapter 4
Chapter 4 : Array
1
Composite Type
A data type is called simple if variables of that type can store only
one value at a time.
Composite type or aggregate type is types that we can use to
define collections of data such that we can manipulate an entire
collection as a unit, but can still refer to individual components of a
given datum by name.
Composite Types are derived from more than one primitive type.
Examples
Array, struct, unions
A data structure is a particular way of storing and organizing
composite data in a computer memory so that it can be used
efficiently 2
Array
5
One-dimensional Array:
6
Declaration of One-dimensionalArray
An array must be declared before it is used. Definition and declaration
tell the compiler the name, type, and dimension of the array.
The general syntax for one-dimensional array is:
type variable_name[dimension/size];
The dimension of the array must be an integer constant or integral
constant expression and must have a value at compilation time.
Example
float score[20]; //score can store 20 float value
char letterGrade[50]; //letterGrade can store 50 char value
int next, score[5], max; // declare arrays and regular
variables together
const unsigned int SIZE=50;
double temp[2*SIZE]; //constant expression for dimension
int i=15, temp[i];
7
Declaration…
8
Array Initialization
Array can be initialized at the time of declaration. There are two option.
Syntax (Option 1):
type array_Name[dimension/size] = { value0, value1, ..,value2};
type array_Name[dimension/size] { value0, value1, ..,value2};
Where
– type specify that what kind of array you are declaring
– array name specify the name of the array
– dimension specifies the size of the array
– value0, value1,…,valueN specify the initial values for array_name[0],
array_name[1],…, array_name[N] respectively.
Dimension is optional. The compiler can determine the dimension from the
list of initial values.
If the number of initial values is less than the dimension specified, the extra
elements of the array will be initialized to 0 for numeric type array or null
character(‘\0’) for character type array. 9
Array…
Example:
int num[5]={3,7,12,24,15]; //equivalent int num[]={3,7,12,24,15];
double distance[5] = {44.14, 720.52, 96.08, 468.78, 6.28};
double distance[5] ={0}; //all elements initialised to zéro
double m[5] ={1.5, 2.3, 4.7}; //m[0], m[1], m[2], m[3], and m[4] are
initialized to 1.5, 2.3, 4.7, 0.0, and 0.0 respectively.
10
Referencing Elements of an Array
An array individual elements can be accessed using an index. For a
one-dimensional array, the first element has an index of 0, the
second element has an index of 1, and so on. Array index starts
from zero.
The general format for accessing an array element in one dimensional
array is:
array_name[index];
Where array_name is the name of the array and index is an integral
constant or any expression that evaluates to an integral value.
Example:
score[3] refers to the fourth element to the array score
11
Referencing…
• An element of an array can be used any where a variable
can be used.
Assuming the following declaration
int arr[20]={1}, i=1, y=3;
An element of array can be assigned:
arr[4] = 55; //The fifth element of the array arr assigned 55
It can be used in an expression(as lvalue and rvalue):
arr[2*i +1] = 3*y + arr[2*i]; //the 4th element is assigned 10
It can be used in an input-output statement:
cin >> arr[18]; //the 19th element will be an integer read from
keyboard
cout << arr[15]; //The 16th will be displayed on the screen
12
Referencing…
Consider the following declaration for the next proposition:
int lista[]={5, 7, 9, 6, 4}, listb[5];
• Attempting to access a nonexistent array element leads to a
serious runtime error (called ‘index out of bounds’ error). The
compiler won’t complain if you assign a value to the
nonexistent element. Your code will compile.
listb[5]=lista[0]; // index out of bounds error
cout << lista[-1] ; // index out of bounds error
• C++ does not allow aggregate operations on an array:
listb=lista; //illegal. Copy element by element
cin >> listb; //illegal! Read element by element
cout << listb; //illegal! Display element by element
13
Array Processing
14
Initialization
15
Filling array from Keyboard
16
Outputting Data Stored in an Array
17
Finding The Smallest, Largest,
Range and Average Value
Write a program that collects the score of students and
determine the smallest, largest, range and average of the
scores
18
Two-dimensional Array:
19
Two-dimensional Arrray
20
Logical View of Two Dimensional Array
The table below shows the sale amount of salesperson for the quarters of
the year. This sales data can be represented using a two dimensional array,
row number representing salesperson and column number representing
quarter. It is a 7 by 4 two dimensional array. This is the logical view of the
programmer, as seven rows of four doubles entries each.
Quarter
Q1 Q2 Q3 Q4
50000 35000 27000 45000 27000 42000 33000 22000 11000 25000 31000 20000
22
Two-dimensional Array Declaration
A two dimensional array has two indices: row index and
column index.
The general syntax for declaring two dimensional array is:
dataType arrayName[rowSize][columnSize];
Where dataType, arrayNname, rowSize, columnSize refer to
the data type, array name, row dimension and column
dimension of the array respectively.
The dimension of the array must be an integer constant or
integral constant expression and must have a value at
compilation time.
double sales[7][4]; //declaration for the previous sale table
This array consists of seven rows and four columns and is
called a 7-by-4 array 23
Initialization of Two-dimensional Array
As with one-dimensional arrays, two-dimensional arrays can
be initialized in their declaration statements by listing the
initial values inside braces and separating them with
commas. Additionally, braces can be used to separate rows.
Syntax:
dataType arrayName[n][m] ={{value00, value01,…,value0m},
{value10, value11,…,value1m},
{value20, value21,…,value2m},
.
.
{valuen0, valuen1,…,valuenm}} .
• Although the commas in initialization braces are always required,
the inner braces can be omitted.
24
Initialization…
• In two-dimensional array, if the array is completely initialized, it
is possible to omit the first dimension(the row size).
• For numerical arrays, if all components of a row aren’t
specified, unspecified ones are set to 0
Example
int table[5][4]={{0, 1, 2, 3}, {10,11,12,13}, {20, 21, 22, 23},
{30, 31, 32, 33}, {40, 41, 42, 43}};
Or
int table[5][4]={0, 1, 2, 3, 10,11,12,13, 20, 21, 22, 23,
30, 31, 32, 33, 40, 41, 42, 43};
Or
int table[][4]={{0, 1, 2, 3}, {10,11,12,13}, {20, 21, 22, 23},
{30, 31, 32, 33}, {40, 41, 42, 43}}; 25
Referencing Array Elements for Two-
dimensional Array
27
Processing Two-Dimensional
Arrays
Processing a two-dimensional array usually requires a nested
loop.
Initialization
• To initialize a particular row (i.e., fifth row) to 0
row=4;
for(i = 0; i < rowSize; i++)
table[row][i]=0;
• To initialize the whole array to some value v
for(i = 0; i < rowSize; i++)
for(j = 0; i < colSize; i++)
table[i][j]=v;
28
Processing…
Inputting
for(i = 0; i < rowSize; i++)
for(j = 0; i < colSize; i++)
cin >> table[i][j];
Outputting
for(i = 0; i < rowSize; i++){
for(j = 0; i < colSize; i++)
cout << setw(5) << table[i][j] << ‘\t’;
cout << endl;
}
29
Example
Write a program that creates a 5 by 6 integer matrix
by accepting the data from the user and then
calculates and displays the sum for each individual
row.
30
Multi-Dimensional Array:
31
Multi-Dimensional Array
32
Using Multi-Dimensional Array
A multi-dimensional array is used in a similar fashion as two-
dimensional array.
Initialization
An n-dimensional array will be initialized during declaration
using n level nested braces for each dimension.
Example for three-dimensional array
int arr[2][3][4] = {{{1,2,3,4}, {5,6,7,8},{9,10,11,12}},
{{13,14,15,16}, {17,18,19,20},{21,22,23,24}}}
It is possible to omit size of first dimension but not other
dimensions
Note: A three-dimensional array is simply an array of two-
dimensional array.
33
Using Multi-Dimensional Array
Referencing
An n-dimensional array will be referenced using n indices for
each dimension. Example
arr[2][3][1]=55;
Processing
An n-dimensional array will be processed using n level nested
loops.
34
Limitation of an Array
35