(UiTM) CSC138 - CHAPTER 1
(UiTM) CSC138 - CHAPTER 1
(UiTM) CSC138 - CHAPTER 1
Lesson Outcomes
At the end of this chapter, student should be able
to:
to
define array
understand requirement of array
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.
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
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.
Example
For example, to tell the compiler to reserve 5
elements for integer array num,
num use the declaration
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.
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.
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.
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
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
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.
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.
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
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:
Example
Printing an array: The following loop outputs the
array sale.
sale For simplicity
simplicity, we assume that the
output goes to the screen.
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;
}
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:
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;
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;
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;
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;
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.
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.
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.";
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
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;
}
}
}
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.
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
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.
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;
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.
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);
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;
}
}
}
}
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).
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.
End of Chapter