(UiTM) CSC138 - CHAPTER 1

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

CSC138

ONE DIMENSIONAL (1D)


ARRAY
Puan Yusnita Sokman

Lesson Outcomes
 At the end of this chapter, student should be able
to:
to
 define array
 understand requirement of array

 know how to declare and initialize an array

 know how to access and print array components

 write program using array – 7 basic algorithms

 know how to pass array as a parameter in function

Puan Yusnita Sokman 1


CSC138

Introduction
 The variables that we have used so far have all had
common characteristic:
characteristic
 Each variable could be used to store only a single
value at a time- called simple data type
 Example:
char grade;
int count;
float marks;

Introduction
 Frequently we may have a set of values, all of the
same data type,
t pe that form a logical group.
gro p
 Example:
Marks Codes Prices
98 x 10.96
87 a 6.43
92 m 2.58
79 n 0.86
called structured data type
 In a structured data type, each data item is a
collection of other data items.

Puan Yusnita Sokman 2


CSC138

Introduction
 An array is a data structure that is a collection of a fixed
number of components wherein all of the components have
the
h same data
d type that
h are accessed d through
h h a common
name.
 All elements of an array is a set of continuous memory
location.
 Each element can be identified by using index or subscript.
 An index is an integer contained within square brackets that
indicates one element of an array’s variable.
 An array elements are numbered beginning with zero.
 The name of the array holds the address of the first array
element.

Type of Array

Array

One- Two-
dimensional dimensional
array array

Puan Yusnita Sokman 3


CSC138

One-Dimensional Array
 A simple list containing individual items of the same
data ttype
pe that is stored in a single gro
group
p name
(array name).
 Also referred as single – dimensional array.
 A one-dimensional array is an array in which the
components are arranged in a list form.
 Can be visualized as a column of variables.
marks[0] 98

marks[1] 87
[0] [1] [2] [3]
marks[2] 92
marks 98 87 92 79
marks[3] 79

Declaring Arrays
 Arrays occupy space in memory.
 The general form
f off declaring a one-dimensional
array is:
dataType arrayName[arraySize];
 The arraySize must be an integer constant greater
than zero.

Puan Yusnita Sokman 4


CSC138

Example
 For example, to tell the compiler to reserve 5
elements for integer array num,
num use the declaration

int num [5]; //num is an array of 5 integers


or Index or subscript
Array name
const int SIZE= 5;
int num [SIZE]; num[0] 4

num[1] 2

num[2] 7

num[3] 3

num[4] 6

Initializing Arrays
 Like any other simple variable, arrays can also be
initiali ed while they
initialized the are being declared.
declared
 When initializing arrays while declaring them, it is
not necessary to specify the size of the array.
 The size of the array is determined by the number of
initial values in the braces.

Puan Yusnita Sokman 5


CSC138

Example
 The statement
i
int li
list[10]
[10] = {0}
{0};
 declares list to be an array of 10 components and
initializes all components to zero
 The statement
int list[10] = {8, 5, 12};
 declares list to be an array of 10 components,
initializes list[0] to 8, list[1] to 5, list[2]
to 12 and all other components are initialized to 0.

Example
 The statement
i
int li
list[]
[] = {5
{5,6,3};
6 3}
 declares list to be an array of 3 components and
initializes list[0] to 5, list[1] to 6, and
list[2] to 3.
 The statement
int list[25]= {4,7};
 declares list to be an array of 25 components. The
first two components are initialized to 4 and 7,
respectively and all other components are initialized to
zero.

Puan Yusnita Sokman 6


CSC138

Example
 The statement
int num[5];
num[0] = -4;
num[1] = 6;
num[2] = 10;
num[3] = 4;
num[4] = 15;
 declares num to be an array of 5 components and
initializes num[0]to -4, num[1]to 6, num[2]to 10,
num[3]to 4 and num[2]to 15.

Accessing Array Component


 The general form (syntax) of accessing an array
component is:
is
arrayName[index]
 Index value specifies the position of the
component in the array
 The [] operator is called the array subscripting
operator.

Puan Yusnita Sokman 7


CSC138

Example
 Consider the following declaration:
i t li
int list[5]
t[5] = {0}
{0};
 This statement declares an array list of 5
components.
 The components are list[0], list[1],...,list[4].
In other words, we have declared 5 variables.
list[0]

list[1]

list[2]

list[3]

list[4]

Example
 The assignment statement:
list[4]
li t[4] = 34 34;
 stores 34 in list[4], which is the fifth component of
the array list.
list[0] 0 list[0] 0

list[1] 0 list[1] 0

list[2] 0 list[2] 0

list[3] 0 list[3] 0

list[4] 0 list[4] 34

Before After

Puan Yusnita Sokman 8


CSC138

Example
 Suppose i is an int variable. Then the assignment
statement:
statement
list[4] = 34;
is equivalent to the assignment statements:
i = 4;
list[i] = 34;

Example
list[0] 10
 Next consider the following statements:
list[1] 35
list[0]
li t[0] = 10
10; list[2]
list[1] = 35; list[3] 45
list[3] = list[0] + list[1]; list[4] 34

 The first statement stores 10 in list[0], the


second statement stores 35 in list[1], and the
third statement add the contents off list[0] and
list[1] and stores the result in list[3].

Puan Yusnita Sokman 9


CSC138

Exercise
 For each of the following, write appropriate
declarations to create the specified array:
arra
 An array listNum[] whose indices are the integers
form 0 to 5 and in which each element is the same
index.
 An array evenList[]whose indices are the integer
from 0 through 9 and for which the array element has
the corresponding even number starting at value 2, 4,
6,8..

Exercise
 Consider the following declaration:
d bl passwords[100];
double d [100]
 In this declaration, identify the following:
 The array name.
 The array size.

 The data type of each array component.

 The range of values for the index of the array.

Puan Yusnita Sokman 10


CSC138

Exercise
 Write C++ statements to define and initialize the
following arrays.
arra s
 Array heights of 10 components of type double.
Initialize this array to the following values: 5.2, 6.3, 5.8,
4.9, 5.2, 5.7, 6.7, 7.1, 5.10, 6.0.
 Array weights of 7 components of type int. Initialize this
array to the following values: 120, 125, 137, 140,
150, 180, 210.
 Array specialSymbols of type char. Initialize this array
to the following values: '$', '#', '%', '@', '&', '! ', '^'.

Exercise
 Write C++ statements to do the following:
 Declare
D l an array beta
b t off 20 components t off type
t double.
d bl
 Output the value of the fifth component of the array beta.

 Set the value of the ninth component of the array beta to


70.50.
 Set the value of the twelth component of beta to four times
the value of the eighth component of beta minus 15.
 Output the value of the last component of beta.

Puan Yusnita Sokman 11


CSC138

Processing One- Dimensional Array


 Some of the basic operations performed on a one-
dimensional array
arra are:
are
 input data
 output(print) data stored in an array

 find the sum and average

 find the largest and/or smallest element

 count number of elements stored in an array (eg. odd


elements)
 Sorting and searching array elements

Processing One- Dimensional Array


 Each of these operations requires the ability to step
thro gh the elements of the arra
through array
 Stepping-through the elements of an array is easily
accomplished by a loop – for loop

Puan Yusnita Sokman 12


CSC138

Example
 This example shows how loops are used to process
arra s
arrays.
 The following declaration is used throughout this
example:
double sale[10];
double sum, average, largestSale;
double smallestSale;
int cntLess30;

Example
 Initializing an array: The following loop initialized
every component of the array sale to 0.0.00

for (int i = 0; i < 10; i++)


sale[i] = 0.0;

Puan Yusnita Sokman 13


CSC138

Example
 Reading data into an array: The following loop
inputs the data into the array sale.
sale For simplicity,
simplicity
we assume that the data is entered at the
keyboard. Assume that the value element of the
sale as follow:

for (int i = 0; i < 10; i++)


cin >> sale[i];

Example
 Printing an array: The following loop outputs the
array sale.
sale For simplicity
simplicity, we assume that the
output goes to the screen.

for (int i = 0; i < 10; i++)


cout << sale[i] << " ";

Puan Yusnita Sokman 14


CSC138

Example
 Finding the sum and average of an array: The
following C++ code finds the sum
s m of the elements
of the array sale and the average sale amount:

sum = 0.0;
for (int i = 0; i < 10; i++)
sum = sum + sale[i];
l [i]
average = sum / 10;

Example
 Counting the number of elements stored in an
array The following C++ code counts
array: co nts the number
n mber
of the elements of the array sale that less than
30.00:

cntLess30 = 0;
f
for (i
(int i = 0
0; i < 10
10; i
i++)
){
if(sale[i] < 30.00)
cntLess30 = cntLess30 + 1;
}

Puan Yusnita Sokman 15


CSC138

Example
 Largest element in the array: The following
statement is to find the largest element in the array.
arra
Assume that the value element of the sale as
follow:

 usethe index of the first occurrence of the largest


element to find the largest sale.

Cont…
 Method 1
int maxIndex = 0;
for (int i = 1; i < 10; i++)
{
if (sale[i] > sale[maxIndex])
maxIndex = i;
}
largestSale = sale[maxIndex];
cout<<"Largest Sale: "<<largestSale;

Puan Yusnita Sokman 16


CSC138

Cont…

Cont…
 Method 2
largestSale
l tS l = sale[0];
l [0]
for (int i = 1; i < 10; i++)
{
if (sale[i] > largestSale)
largestSale = sale[i];
}
cout<<"Largest Sale: "<<largestSale;

Puan Yusnita Sokman 17


CSC138

Example
 Smallest element in the array: The following
statement is to find the smallest element in the
array.

Cont…
 Method 1:
int
i t minIndex
i I d = 0;
0
for (int i = 1; i < 10; i++)
{
if (sale[i] < sale[minIndex])
minIndex = i;
}
smallestSale = sale[minIndex];
cout<<"Smallest Sale: "<<smallestSale;

Puan Yusnita Sokman 18


CSC138

Cont…
 Method 2:
smallestSale
ll tS l = sale[0];
l [0]
for (int i = 1; i < 10; i++)
{
if (sale[i] < smallestSale)
smallestSale = sale[i];
}
cout << "Smallest Sale: "
<< smallestSale;

Array Index Out of Bounds


 If we have the statements:
double num[10];
int i;
 The component num[i] is a valid index if i = 0, 1,
2, 3, 4, 5, 6, 7, 8, or 9
 The index of an array is in bounds if the index
>=0 and the index <= arraySize-1
 If either the index < 0 or the index >
arraySize-1, then we say that the index is out of
bounds.

Puan Yusnita Sokman 19


CSC138

Exercise 1
 Write a complete C++ program using a one-
dimensional arra
array to perform the following
following:
 declare an array named voltage to store 50 floating-
point voltages.
 input values for voltages into the array named voltage.

 calculate and display the total and average of


voltages.
voltages
 find and display the highest and lowest voltage.

 count and display the values of voltages that exceed


100 volts.

Exercise 2
 Create an array of double of size 30 to store daily
temperatures in Celsius for one month.
month Write a C++
program to do the following operations on the array:
 prompt the user to input the daily temperatures and stores it
into the array.
 determine and display the hottest and the coldest
temperature of the month.
 determine and display the difference between the hottest
and the coldest temperature of the month.
 determine and display the average temperature of the
month.

Puan Yusnita Sokman 20


CSC138

Searching Arrays – Linear Search


 A very simple algorithm
 A known as sequential search
Also
 Algorithm:
 Searching a list for a given value, starting from the first
array element.
 Compare each element in the array with value being
searched for.
 Continue the search until value is found or no more
element is left in the list.
 Ifthe value being searched for is not in the array, the
algorithm will unsuccessfully search to the end of the array.

Example
double searchValue;
cout << "Enter the search value: "; cin >> searchValue;
bool found = false; //flag to indicate of search value
int index = 0; //used as a subscript to search array
while (index < SIZE && !found)
{
if (sale[index] == searchValue) //if the value is found
found = true; //set the flag
else
index++; //go to the next element
}
if (found) //if the value is found
found, index contains the
//subscript of the specified value in the array
cout << "The search value is found at element "
<< index << " in the array.";
else //if the value is not found
cout << "The search value does not exist in the array.";

Puan Yusnita Sokman 21


CSC138

Sorting of Arrays
 The process of arrangging the arrays in some order
is called sorting of arrays.
arra s
 There are two type of orders:
 ascending order (data are sorted from lowest to
highest)
 descending order (data are sorted from highest to
l
lowest)
t)
 Two type of sorting techniques:
 the bubble sort
 the selection sort

The Bubble Sort


 The very commonly and widely used sorting
techniq e to arrange data in ascending or
technique
descending order.
 It is also known as the exchange sort.
 The bubble sort repeatedly visits the elements of an
array and compares the two adjacent elements.

Puan Yusnita Sokman 22


CSC138

The Bubble Sort


 Algorithm:
 it
i will
ill compare two adjacent
dj elements,
l
 if the first element is greater than the second element then it
will swap (exchange) them – if we wanted to sort an array
in an ascending order.
 if the first element is less than the second element then it will
swap (exchange) them – if we wanted to sort an array in an
d
descending
di order.
d
 Itcontinues to swap the elements until no more swaps
are required, which mean the given array is sorted.

Example
double temp;

//specified no of passes
for(int i = 0; i < (SIZE - 1); i++) {
//specified the no of iteration
for(int j = 0; j < (SIZE - 1); j++)
{
//arrange data in ascending order
if(sale[j] > sale[j+1])
{
t
temp = sale[j];
l [j]
sale[j] = sale[j+1];
sale[j+1] = temp;
}
}
}

Puan Yusnita Sokman 23


CSC138

Exercise
 Declare an array named salesRecord to store sales
made for the year.
ear Then
Then, accept sales data and
store them into the array. Next, for any sales made
which is less than RM 100, display the month and
the sales amount.

Exercise
 Given the following a set of values :
10,13,-23,-51,55,5,60,40,-20,-75,45,-1,35,44,89,
6 9
-90,40,11,-21,-100
 Declare and initialize a one-dimensional array to store
the given values.
 Display and count the negative values in the array.

 Display the values in the array in ascending order.

Puan Yusnita Sokman 24


CSC138

Array and Function


 How are arrays passed as parameters to functions?
 By
B reference
f only:
l IIn C++
C++, arrays are passed d by
b
reference only.
 Because arrays are passed by reference only, you do
not use the symbol & when declaring an array as a
formal parameter.
 When declaring a one
one-dimensional
dimensional array as a formal
parameter, the size of the array is usually omitted.
 If you specify the size of the one-dimensional array when it
is declared as a formal parameter, the size is ignored by
the compiler.

Example
 Write a program that uses a one-dimensional array
to store the temperat
temperatures
res for each month of the
year. The program should output
 the average temperatue of the year,
 the highest temperature of the year

 the lowest temperature of the year

Puan Yusnita Sokman 25


CSC138

Example
 Your program must consist of the following functions:
 Function
F i readTemp():
dT () This
Thi ffunction
i receives
i an array
and its size through its parameter. This function then
reads and stores the temperatures into the array.
 Function aveTemp(): This function receives an array
and its size through its parameter. This function then
calculates and returns the average g temperature
p of the
year.

Example
 Function indexHighTemp(): This function receives
an array and its size through its parameter
parameter. This function
then determines and returns the index of the highest
temperature in the array.
 Function lowTemp(): This function receives an array
and its size through its parameter. This function then
determines and returns the lowest temperature in the
array.
 Function displayTemp(): This function receives an
array and its size through its parameter. This function
then displays the contents of the array.

Puan Yusnita Sokman 26


CSC138

Example
 Function searchTemp(): This function receives an
array its size through its parameter and a value of
array,
temperature to be searched. This function then
determines whether the temperature exists in the array
or not. If the value is found, its array subscript is
returned, otherwise, -1 is returned indicating the value
was not in the array.

Cont…
int searchTemp(double t[], int s, double tempSearch);
int main(){
const int SIZE = 12;
double temp[SIZE];
:
//linear @ sequential search
double searchValue;
cout << "Enter the temp value to be searched: ";
cin >> searchValue;

int result = searchTemp(temp, SIZE, searchValue);


if(result == -1)
cout << "The search value does not exist in the array.";
else
cout << "The search value is found at element "
<< result << " in the array.";
:
}

Puan Yusnita Sokman 27


CSC138

Cont…
int searchTemp(double t[], int s, double tempSearch)
{
b l found
bool f d = ffalse;
l
int loc = 0;
while (loc < s && !found)
{
if (t[loc] == tempSearch)
found = true;
else
loc++;
}

if (found)
return loc;
else
return -1;
}

Example
 Function sortTemp(): This function receives an array
and its size through its parameter
parameter. This function then
performs an ascending order bubble sort on array.

Puan Yusnita Sokman 28


CSC138

Cont…
void sortTemp(double t[], int s);

int main(){
const int SIZE = 12;
double temp[SIZE];
:
//bubble sort
cout << "\n\nThe unsorted values are: \n";
displayTemp(temp, SIZE);

//sort the values


sortTemp(temp,
p p SIZE);

cout << "\nThe sorted values are: \n";


displayTemp(temp, SIZE);
:
}

Cont…
void sortTemp(double t[], int s)
{
d bl temp;
double
for(int i = 0; i < (s-1); i++)
{
for(int j = 0; j < (s-1); j++)
{
if(t[j] > t[j+1])
{
temp = t[j];
t[j] = t[j+1];
t[j+1] = temp;
}
}
}
}

Puan Yusnita Sokman 29


CSC138

Exercise
 The following data is about student’s height which
has been collected from 20 students.
st dents The students’
st dents’
heights are measured in centimeter (cm).

 Your program must consist of the following functions:


 void readData(int[], int);
 This function receives an array and its size through its parameter. This
function then prompts the user for the student’s height and save the
values in the array.

Exercise
 void findHeight(int[], int, int&);
 This function receives an array and it size through its parameter. This
function then determines and returns through its parameter, the height
for tallest student.
 int countFrequency(int[], int);
 This function receives an array and its size through its parameter. This
function then returns the number of students (frequency) whose height
is in the range of 161–180cm.
 void
i sortDescHeight(int[],
i i i
int);
 This function receives an array and its size through its
parameter. This function then performs a descending order
bubble sort on array.

Puan Yusnita Sokman 30


CSC138

End of Chapter

Puan Yusnita Sokman 31

You might also like