0% found this document useful (0 votes)
12 views38 pages

Understanding Arrays in Programming

Chapter Four discusses arrays as a composite data type used to store collections of data in programming. It covers the declaration, initialization, and processing of one-dimensional and two-dimensional arrays, including examples and syntax. The chapter also highlights the limitations of arrays, such as fixed dimensions and memory management issues.

Uploaded by

Abel Blaze
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views38 pages

Understanding Arrays in Programming

Chapter Four discusses arrays as a composite data type used to store collections of data in programming. It covers the declaration, initialization, and processing of one-dimensional and two-dimensional arrays, including examples and syntax. The chapter also highlights the limitations of arrays, such as fixed dimensions and memory management issues.

Uploaded by

Abel Blaze
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

CHAPTER FOUR

ARRAYS

BY: JOSEPH W.
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.
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
CONTINUED
In general, only the array itself has a
num[0] in
symbolic name, not its elements. t
num[1]
Each element is identified by an index
num[2]
which denotes the position of the element
num[3]
in the array.
num[4]
The number of elements in an array is
num[5]
called its dimension. The dimension of an
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],…
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
One-Dimensional Array
DECLARATION OF ONE-DIMENSIONAL ARRAY
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
CONTINUED

• 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.
ARRAY INITIALIZATION
Array can be initialized at the time of declaration. There are two option.
Syntax:
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.
CONTINUED
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};
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.
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


CONTINUED
• 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
CONTINUED
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
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
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;
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];
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];
FINDING THE SMALLEST ELEMENT
OTHER WAY
Two-Dimensional Array
TWO-DIMENSIONAL ARRAY

• Two-dimensional array: collection of a fixed number of


components (of the same type) arranged in two dimensions
• Sometimes called matrices or tables
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.
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.

• The organization of this array in memory is as 28 consecutive


double elements.
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
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.
CONTINUED
• 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}};
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 3 rd row and the 4th columnto the array score
CONTINUED

• An element of a two-dimensional array can be used any where a


variable can be used.
Assuming the following declaration
int arr[20][30]={1}, 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[2*i +1][3] = 3*y + arr[2*i][2]; // The element at row index 3 and
//column index 3 is assigned 55
It can be used in an input-output statement:
cin >> arr[2][3];
cout << arr[5][2];
PROCESSING TWO-DIMENSIONAL ARRAY
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 0
for(i = 0; i < rowSize; i++)
for(j = 0; i < colSize; i++)
CONTINUED
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;
}
EXAMPLE

• Write a program that creates a 5 by 6 integer matrices by


accepting the data from the user and then calculates and
displays the sum for each individual row.
Multi-Dimensional Array
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];
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
CONTINUED
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.
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 .
Thank You !!

You might also like