0% found this document useful (0 votes)
64 views63 pages

One-Dimensional Arrays in C++

This chapter discusses one-dimensional arrays. Key points include: - Arrays allow storing a collection of related data of the same type. - One-dimensional arrays store elements in a single list accessed by index. - Arrays are declared with the data type, array name, and size. Arrays can be initialized during declaration. - Elements are accessed using the array name and index in brackets. Loops are commonly used to iterate through arrays to perform operations like summing elements.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views63 pages

One-Dimensional Arrays in C++

This chapter discusses one-dimensional arrays. Key points include: - Arrays allow storing a collection of related data of the same type. - One-dimensional arrays store elements in a single list accessed by index. - Arrays are declared with the data type, array name, and size. Arrays can be initialized during declaration. - Elements are accessed using the array name and index in brackets. Loops are commonly used to iterate through arrays to perform operations like summing elements.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CHAPTER 3

ONE-DIMENSIONAL ARRAYS
Learning Outcomes
› Atthe end of this chapter, student
should be able to:
›  learn about the use of arrays to store data
›  declare and initialize an array
›  manipulate data in the arrays
›  use string functions to process C-strings
›  pass an array as a parameter to a function
Introduction
›  The
variable that we have used so far
have all had common 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 (cont.)
›  Frequently
we may have set of values, all of
the same data type, that form a logical
group.
›  Example:
Marks Codes Prices
98 x 10.96
87 a 6.43
92 m 2.58
79 n 0.86

called structural data type


›  In
a structured data type, each data items is a
collection of other data items.
Introduction (cont.)
›  An array is a data structure that is a collection of a
fixed number of components wherein all of the
components have the same data type that are
accessed through 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.
Types of Array

Array

One- Two-
dimensional dimensional
array array
One-Dimensional Array
›  Asimple list containing individual items of
the same data type that is stored in a single
group name (array name).
›  Also referred as single – dimensional array.
›  Aone-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 syntax of declaring a one-
dimensional array is:
dataType arrayName [arraySize];
›  The
arraySize must be an integer constant
greater than zero.
Example 1
›  For
example, to tell the compiler to reserve 5
elements for integer array 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
›  Likeany other simple variable, arrays can
also be initialized while they are being
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 2
›  The statement
int list[10] = {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.
›  The statement
int list[] = {5, 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.
Example 3
›  The statement
int list[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 [4] to 15.
Accessing Array Component
›  The
general syntax of accessing an array
component is:
arrayName[index]
›  Index
value specifies the position of the
component in the array.
›  The[ ] operator is called the array
subscripting operator.
Example 4
›  Consider the following declaration:
int list[5] = {0};
›  This
statement declares an array list of 5
components.
›  Thecomponents 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 5
›  The assignment statement:
list[4] = 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 6
›  Suppose
i is an int variable. Then the
assignment statement:
list[4] = 34;
is equivalent to the assignment statements:
i = 4;
list[i] = 34;
Example 7
›  Next consider the following statements:
list[0] = 10; list[0] 10
list[1] 35
list[1] = 35;
list[2]
list[3] = list[0] + list[1]; list[3] 45
list[4] 34

›  Thefirst statement stores 10 in list[0],


the second statement stores 35 in list[1],
and the third statement add the contents
of list[0] and list[1] and stores the
result in list[3].
Processing One-Dimensional Array
›  Some
of the basic operations performed on a
one-dimensional array are:
›  Initialize

›  Input data
›  Output data stored in array
›  Find the sum and average
›  Find the largest and/or smallest element
›  Eachof these operations requires the ability to
step through the elements of the array.
›  Stepping-through
the elements of an array is
easily accomplished by a loop – for loop
Example 8a
›  This
example shows how loops are used to
process arrays.
›  Thefollowing declaration is used
throughout this example:
double sale[10];
int i;
double sum, average, largestSale;
Example 8b
›  Initializingan array: The following loop
initialized every component of the array
sale to 0.0

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


sale[i] = 0.0;
Example 8c
›  Reading data into an array: The following
loop inputs the data into the array sale. For
simplicity, we assume that the data is
entered at the keyboard.

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


cin >> sale[i];
Example 8d
›  Printing
an array: The following loop outputs
the array sale. For simplicity, we assume
that the output goes to the screen.

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


cout << sale[i] << “ ”;
Example 8e
›  Finding the sum and average of an array:
The following C++ code finds the sum of the
elements of the array sale and the
average sale amount.

sum = 0.0;
for(i = 0; i < 10; i++)
sum = sum + sale[i];
average = sum / 10;
Example 8f
›  Largest element in the array:
The following statement is to find the largest
element in the array. Assume that the value
element of the sale as follow:

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

sale 12.50 8.35 19.00 25.00 14.00 39.43 35.90 98.23 66.65 35.64
Example 8f (cont.)
›  Method 1: Use the index (location of the largest element
in the array) of the first occurrence of the largest element
to find the largest sale.

int maxIndex = 0; //assume that the first


//element in the list is the
//largest element
for(index=1; index<10; index++)
{
if(sale[maxIndex] < sale[index])
maxIndex = index;
}
largestSale = sale[maxIndex];
cout<<“Largest Sale: ”<<largestSale;
Example 8f (cont.)
sale[maxIndex]
index maxIndex sale[maxIndex] sale[index]
< sale[index]
1 0 12.50 8.35 12.50<8.35 is false
12.50<19.60 is true;
2 0 12.50 19.60
maxIndex = 2

19.60<25.00 is true;
3 2 19.60 25.00
maxIndex = 3
4 3 25.00 14.00 25.00<14.00 is false
25.00<39.43 is true;
5 3 25.00 39.43
maxIndex = 5
6 5 39.43 35.90 39.43<35.90 is false
39.43<98.23 is true;
7 5 39.43 98.23
maxIndex = 7
8 7 98.23 66.65 98.23<66.65 is false
9 7 98.23 35.64 98.23<35.64 is false
Example 8f (cont.)
›  Method 2

largestSale = sale[0]; //assume the first


//element is the
//largest
for(i=1; i<10; i++)
{
if(sale[i] > largestSale)
largestSale = sale[i];
}
cout<<“Largest Sale: ”<<largestSale;
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
›  Theindex of an array is in bounds if the index
>= 0 and the index <= arraySize – 1
›  If
either the index < 0 and the index >
arraySize – 1, then we say that the index is
out of bounds.
Array Index Out of Bounds (cont.)
›  C++ doesn’t check whether the index value is
within the range.
›  A loop such as following can set the index out of
bounds:
for(int index=0; index<=10; index++)
list[index];
We assume list is an array of 10 components. When
index becomes 10, the loop test condition index<=10
evaluates to true and the body of the loop executes,
which result in storing 0 in list[10]. Logically, list[10]
doesn’t exist.
›  This
resulting in altering/accessing the data of a
memory location that you never intended to
modify/access.
Exercise 1
›  Writeone or more statements that perform
the following tasks for an array called
fractions:
›  Define
a constant integer variable
arraySize initialized to 10.
›  Declarean array with arraySize elements of
type double, and initialize the elements to 0.
›  Name the fourth element of the array.
›  Refer to array element 4.
›  Assign the value 1.667 to array element 9.
Exercise 1 (cont.)
›  Assign
the value 3.333 to the seventh
element of the array.
›  Print array elements 6 and 9.
›  Print
all the array elements using for
statement. Define the integer variable i as
control variable for the loop. Show the
output.
Exercise 2
›  Using
the declaration of array alpha, write
C++ statements for the following:
›  Output the value of the 10 element of the
array alpha.
›  Setthe value of 5 element of the array alpha
to 35.
›  Setthe value of the 4 element of the alpha to
three times the value of the eight element
minus 57.
›  Output alpha so that 5 elements per line are
printed.
Exercise 3
›  Assuming
that the array NUMBER[] is initially
as shown below:
NUMBER[]
[0] [1] [2] [3] [4]
36 51 18 110 89

›  Showthe contents of the array elements


after each of the following program
segments is executed. Assume a) and b) is
executed independently.
Exercise 3 (cont.)
a)  temp = NUMBER[0];
NUMBER[0] = NUMBER[2];
NUMBER[2] = temp;

NUMBER[]
[0] [1] [2] [3] [4]
Exercise 3 (cont.)
b)  temp = NUMBER[0];
for(int i=0; i<3; i++)
NUMBER[i] = NUMBER[i+1];
NUMBER[4] = temp;

NUMBER[]
[0] [1] [2] [3] [4]
Exercise 4
›  numis an integer array of ten elements.
Write C++ statements to do the following:
›  Declare num.
›  Read all elements of num.
›  Display all positive integers in num.
Exercise 5
›  Write a program that accepts a list of integers
and places them into an array. When the enter
button is pressed, the list of integers in the array
is displayed in a reverse order. Below is the
sample output of the program.
Exercise 6
›  Given declaration as follows:
const int NUMARRAY = 5;
float LIST[NUMARRAY];
›  How many elements are in LIST array?
›  Using a for statement, write a program to assign the
value of 1.2, 3.2, 5.5, 7.1, 5.5 from user input to the
LIST array.
›  Based on the above question, what is the value of
x?
x = int (LIST[l]) + LIST[4] / LIST[3] * pow (LIST[2] ,3);
Exercise 7
›  Write
a complete C++ program using a one-
dimensional array to perform the 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.
›  find and display the highest and lowest voltage.
›  count and display the values of voltages that
exceed 100 volts.
Exercise 8
›  Create an array of double of size 30 to store
daily temperatures in Celsius for one 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.
Searching an Array for a Specific Item
›  Searching
a list for a given item is one of the
most common operations performed on a list.
›  Sequential search (or linear search):
›  Searching a list for a given item, starting from the
first array element.
›  Compare each element in the array with value
being searched for.
›  Continue the search until item is found or no more
data is left in the list.
Searching an Array for a Specific Item
(cont.)
›  Example:

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
numList 35 12 65 78 45 34 17 30 98 22

›  Suppose that you want to determine whether


17 is in the numList.
Searching an Array for a
Specific Item (cont.)
int seqSearch(const int numList[], int size, int searchItem)
{
bool found = false;
int loc = 0;
while (loc < size && !found)
{
if (numList[loc] == searchItem)
found = true;
else
loc++;
}
if (found)
return loc;
else
return -1;
}

›  If the function seqSearch returns a value greater than or equal to 0, it is a


successful search; otherwise, it is an unsuccessful search.
Sorting Arrays
› Sortingis the process of putting data in
order; either numerically or
alphabetically.
› Theprocess of sorting an array requires
the exchanging of values.
› Mustbe careful that no values are lost
during this exchange.
Sorting Arrays (cont.)
›  Consider the following dilemma:
Suppose that grade[1] = 10 and
grade[2] = 8 and you want to
exchange their values.
›  You could NOT just do this:
grade[1] = grade[2];
grade[2] = grade[1];
›  The value stored in grade[1] is erased and
replaced with grade[2].
›  The result, both grade[1] and grade[2]
now have the same value.
›  The value in grade[1] is lost!
Sorting Arrays (cont.)
›  To
swap 2 values, must use a third variable to
temporarily hold the value.

temp = grade[1];
grade[1] = grade[2];
grade[2] = temp;

›  This
process successfully swaps the values
without the loss of any values.
Bubble Sort
›  As elements are sorted, they gradually “bubble” or
rise to their proper location in the array.
›  Repeatedly compares adjacent/next elements of
an array.

84 69 76 86 94 91

›  The sorting process continues until the last two


elements of the array are compared and swapped
if out of order.
Bubble Sort (cont.)
›  The
table below is an example of sorting
process for descending order:

Array at
84 69 76 86 94 91
beginning
After Pass 1 84 76 86 94 91 69
After Pass 2 84 86 94 91 76 69
After Pass 3 86 94 91 84 76 69
After Pass 4 94 91 86 84 76 69
After Pass 5
94 91 86 84 76 69
(done)
Bubble Sort (cont.)
›  Whenthe first pass through the array is
complete, the bubble sort returns to
elements one and two and start the
process all over again.
›  The
bubble sort knows that it is finished
when it examines the entire array and no
“swaps” are needed.
Example 9a
const int array_size = 4;
int x[array_size] = {10, 40, 13, 8};
int hold;

//Bubble Sorting begins


for (int passes = 1; passes < array_size; passes++)
{
for (int j = 0; j < array_size - passes; j++)
{
if (x[j] > x[j+1])
{
hold = x[j];
x[j] = x[j+1];
x[j+1]=hold;
}
}
} //Bubble Sorting finished
Explanation
›  Theprogram will used nested loop to
perform sorting.
›  The
iterations of outer loop will specified the
number of passes and the inner loop will
specify the number of iterations.
Explanation (cont.)
›  First Pass:
0 1 2 3

10 40 13 8

›  In the first pass, the value i=0 and the inner loop came into action,
it will perform 3 iterations and check the condition of the following
block of statements.

if (x[j] > x[j+1])


{
hold = x[j];
x[j] = x[j+1];
x[j+1]=hold;
}
Explanation (cont.)
›  Iteration no. 1:

0 1 2 3

10 40 13 8
Unsorted list

›  Atfirst iteration, the value j=0 and the value


j+1=1. Therefore it will compare the values of
zero index and the first index of an array.
›  As
we can see that the at value zero index is
smaller than the first index, therefore the array
remains the same.
Explanation (cont.)
›  Iteration no. 2:
0 1 2 3

10 40 13 8
›  At second iteration, the value j=1 and the value j+1=2.
Therefore it will compare the values of first index and the
second index of an array.
›  As we can see that the value at second index is smaller
than the first index, therefore the elements of first and
second will be swap, the new array looks like:

0 1 2 3

10 13 40 8
Explanation (cont.)
›  Iteration no. 3:
0 1 2 3

10 13 40 8

›  At third iteration, the value j=2 and the value j+1=3.


Therefore it will compare the values of second index and
the third index of an array.
›  As we can see that the value at third index is smaller
than the second index, therefore the elements of second
and third will be swap, the new array looks like:
0 1 2 3

10 13 8 40
›  As you can see that the end of the first pass, the largest
value is placed at the last index.
Explanation (cont.)
›  Second Pass:
›  Iteration no. 1:
0 1 2 3

10 13 8 40

›  At first iteration, the value j=0 and the value j+1=1.


Therefore it will compare the values of zero index and the
first index of an array.
›  As we can see that the value at zero index is smaller than
the first index, therefore the array remains the same.
Explanation (cont.)
›  Iteration no. 2:
0 1 2 3

10 13 8 40

›  At second iteration, the value j=1 and the value j+1=2.


Therefore it will compare the values of first index and the
second index of an array.
›  As we can see that the value at second index is smaller
than the first index, therefore the elements of first and
second will be swap, the new array looks like:

0 1 2 3

10 8 13 40
Explanation (cont.)
›  Iteration no. 3:
0 1 2 3

10 8 13 40

›  At third iteration, the value j=2 and the value j+1=3.


Therefore it will compare the values of second index and
the third index of an array.
›  As we can see that the value at second index is smaller
than the third index, therefore the array remains the
same.
Explanation (cont.)
›  Third Pass:
›  Iteration no. 1:
0 1 2 3

10 8 13 40
›  At first iteration, the value j=0 and the value j+1=1. Therefore
it will compare the values of zero index and the first index of
an array.
›  As we can see that the value at first index is smaller than the
zero index, therefore the elements of zero and first will be
swap, the new array looks like:
0 1 2 3

8 10 13 40
›  At this point the loop is completed. The outer loop will also
terminate and the array is sorted in ascending order
Exercise 9
›  Sort the list into alphabetical order:
G, C, N, A, P, C

›  Sort the list of names below in descending order.


Amirul, Syafiqah, Ah Chong, Siew Ling, Suraya, Kumar
Parallel Arrays
›  Two or more arrays are called parallel if
their corresponding components hold
related information.
›  Refer to Example 6.7 (pg. 144)
Exercise 10
Write a complete C++ code to do the following:
›  Declare two arrays (each with 5 elements) to store
each of the following data:
›  First array to store the student’s name.
›  Second array to store the final examination score.
›  Read data into both arrays.
›  Display each student names together with their
score in descending order.
›  Calculate and display the average score.
›  Count and display the number of students where
their score above the average.
›  Determine the student with the lowest score. Display
the name and the scores.
End of One-dimensional
Array
Any Questions???

You might also like