Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Problem Solving I Chapter 4

Download as pdf or txt
Download as pdf or txt
You are on page 1of 39

CS221 : Computer Programming I

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

Array is an elementary data structure that exists as built-in in most


programming languages.
Array is a collection structure composed of a fixed number of
elements wherein all of the elements have the same data type.
The elements are stored in contiguous computer memory so that
it allows random access of its elements, i.e. elements can be
accessed using indexing by address calculation.
Arrays are suitable for representing composite data which consist
of many similar, individual items. Examples include: a list of names,
a table of world cities and their current temperatures, or the
monthly transactions for a bank account.
3
Array
In general, only the array itself has a num[0]
int
symbolic name, not its elements.
num[1]
Each element is identified by an index
num[2]
which denotes the position of the element
num[3]
in the array.
The number of elements in an array is num[4]

called its dimension. The dimension of an num[5]


array is fixed and predetermined; it cannot
be changed during program execution.
(see side figure)An array of 6 integers of type int as a collection
referred by a name num and individual elements referred by
subscript as num[0], num[1],…
4
Array Categorization

Array can be categorized into two part


1) One dimensional Array:
collection of a fixed number of elements (of the same
type) arranged in one dimension as a list
2) Multi dimensional :
collection of a fixed number of components (of the
same type) arranged in multi dimensions

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]; //invalid declaration 7
Declaration…

Declaration and definition only reserve space for the


elements in the array. No values will be stored. If we want to
store values in the array, we must either initialize the
elements, read value from the keyboard, or assign value to
each individual elements.

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
9
character(‘\0’) for character type array.
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 third 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 9
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

Some basic operations performed on a one-dimensional


array are:
• Initialization
• Filling array from keyboard
• Outputting data stored in an array
• Finding the largest and/or smallest element
• Each operation requires ability to step through the
elements of the array
• Easily accomplished by a loop

14
Initialization

A loop is very useful for initialization of an array specially if


the values of the array follows some pattern:
Example:
int odd[50]
for(int i = 0; i < 50; i++)
odd[i] = 2*i + 1;

15
Filling array from Keyboard

A loop is very useful to obtain the values of the array from


the keyboard:
Example:
float score[60]
for(int i = 0; i < 60; i++){
cout << “score[“ << i << “] = “;
cin << score[i];
}

16
Outputting Data Stored in an Array

A loop is very useful to display the values of the array :


Example:
float score[60];
for(int i = 0; i < 60; i++)
cout << “score[“ << i << “] = “ << score[i]<<endl;

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
Range Based For Loop and Array
A range based style loop is designed to cycle through a collection of
objects, such as an array, vector in strictly sequential fashion, from start
to finish.
The general form of the for-each version of the for is shown here:
for(range_decleration : collection){
statements
}
There are two types of ranged based loops
1. Normal Iterators: an ordinary temporary variable is declared as the
iterator, and the iterator gets a copy of the current loop item by value.
Any changes made to the temporary copy will not get reflected in the
original iterable.
Syntax
for (datatype iterator : collection) {
// operation are performed here 19
}
Range Based For Loop…

int arr[]={12, 20, 50,54, 72, 101};


for(int x:arr){
cout<<x<<“ “;
}
The above code prints all the values in arr separated
by space.

20
Range Based For Loop…
2. Reference Iterators: Reference iterators are declared as a reference
variable, and the iterator gets the value of the current item by reference.
So the changes made inside the loop are definitely get affected in the
original container itself.Syntax
for (datatype & iterator : collection) {
// operation are performed here
}
int arr[]={12, 20, 50,54, 72, 101};
for(auto & x:arr){
x=2*x;
}

21
Two-dimensional Array:

22
Two-dimensional Arrray

Two-dimensional array: collection of a fixed


number of components (of the same type)
arranged in two dimensions
Sometimes called matrices or tables

23
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

Abebe 50,000.00 35,000.00 27,000.00 45,000.00


Salesperson

Almaz 27,000.00 42,000.00 33,000.00 22,000.00


Hagos 11,000.00 25,000.00 31,000.00 20,000.00
Tesfaye 47,000.00 36,000.00 26,000.00 32,000.00
Roman 55,000.00 45,000.00 52,000.00 50,000.00
Eden 47,000.00 45,000.00 48,000.00 52,000.00
Solomon 31,000.00 34,000.00 29,000.00 52,000.00 24
Physical View of Two-dimensional
Array

The organization of the array in memory (The physical view


of the programmer) is however still the same (a contiguous
sequence of elements) as the one-dimensional array.

50000 35000 27000 45000 27000 42000 33000 22000 11000 25000 31000 20000

row1 row2 row3

The organization of this array in memory is as 28 consecutive


double elements.

25
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 26
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.

27
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},
28
{30, 31, 32, 33}, {40, 41, 42, 43}};
Referencing Array Elements for Two-
dimensional Array

The individual elements of a two-dimensional array can be


accessed using two indices: row and column indices.
Syntax:
array_name[rowIndex][columnIndex];
Where array_name is the name of the array and rowIndex and
columnIndex are an integral constant or any expression that
evaluates to an integral value.
Example:
double sale[7][4];
sale[2][3] refers to the element at the 3rd row and the 4th columnto
the array score
29
Referencing…
• An element of a two-dimensional array can be used any
where a variable can be used.
Assuming the following declaration
int arr[2][5]={1,2,3,5,5,5,4,5,3,6}, i=1, y=3;
It can be assigned:
arr[1][4] = 55; //The element at row index 1 and column index4 is
// assigned 55
It can be used in an expression(as lvalue and rvalue):
arr[0][2*i+1] = 3*y + arr[2*i][2]; // The element at row index 0 and
//column index 3 is assigned 12
It can be used in an input-output statement:
cin >> arr[1][3];
cout << arr[0][2];
30
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;
31
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;
}

32
Range Based For Loop For 2D array
int b[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
for (auto& outer : b) {
for (auto& inner : outer) {
std::cout << inner << std::endl;
}
}
On the outer loop the auto and the & are required so that the array
doesn't decay to a pointer.

33
Example
Write a program that calculates and displays the
sum for each individual row, column, and the two
diagonal of a square matrices of integer. The
dimension of the square matrix is known to be not
greater than 10. The actual dimension must be
accepted from the user. The matrix is populated by
accepting the data from the user.

34
Multi-Dimensional Array:

35
Multi-Dimensional Array

A multi-dimensional array can have three, four or more


dimensions.
Multidimensional Array Declaration
SYNTAX
Type Array_Name[Dim_1][Dim_2]...[Dim_Last];
EXAMPLES
double three_d_picture[10][20][30];

36
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.
37
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.

38
Limitation of an Array

The dimension of an array is fixed and predetermined at


compile time; it cannot be changed during program
execution. It can’t be resized. For this reason the
programmer is forced to estimate the size of the array which
may result in overestimation and hence waste of memory
space or underestimation in which case the program is
unable to hold all the information required and ultimately
crash .

39

You might also like