Vous êtes sur la page 1sur 11

CSC138

Lecture Note

CSC138 STRUCTURED PROGRAMMING


TOPIC 1
ONE-DIMENSIONAL ARRAYS
Introduction
An array is a collection of am fixed number of components or values all of the same data type. A onedimensional array is an array in which the components are arranged in a list form. For example, an
array may be used to store a group of numbers, a group of characters, a group of students marks or a
group of students information.
An array is used when similar operations are required for a group of data. Coding the program will be
easier and simple if an array is used. In most cases, these data have to be stored so that it can be
used in the next operation.
For example, the following program will input five numbers and display them in reverse order, without
using an array.
void main()
{
int no1, no2, no3, no4, no5;
cout<<"Enter 5 numbers : ";
cin >> no1 >> no2 >> no3 >> no4 >> no5;

cout<<"The numbers in the reverse order is : "


<< no5 <<" "<< no4 <<" "<< no3 <<" "<< no2 <<" "<< no1;

The program uses five variables with five different identifiers at three different places. Try to solve the
same problem with a hundred numbers (I will not do that if I have to use 100 variables with 100
identifiers).
A loop statement is not used in this program because data have to be kept after it is being read. The
process for these numbers is done after all numbers have been obtained from the user. Using a loop
will allow the use of only one variable with one identifier. When the next loop is executed, the previous
number or value will be replaced with a new number.
On the other hand, a loop statement is in favor if an identifier is used to represent all numbers. The
variable, which uses an identifier for a group of memory locations, is known as an array. The following
example program uses an array to display the five numbers in a reverse order.
void main()
{ int no[5], i;
cout<<"Enter 5 numbers : ";
for(i=0; i<5; i++)
{
cin >> no[i];
}
cout<<"The numbers in the reverse order is : "
for(i=4; i>=0; i--)
{
cout << no[i] <<" ";
}
}
1

CSC138

Lecture Note

The program uses an array of five elements name no. Elements can also be referred to as location.
The numbers that the user inputs are inserted or stored into elements of an array one by one in the
first loop structure.
Each element of the array is referred to using an index. The value of index changes at every loop, but
the name of the array does not changed. After the execution of a loop, the value i is increased or
decreased. It reflects the element, which will be referred at the following loop.
Try to solve the problem using one hundred numbers. (Tips: only 3 statements in program, which will
be replaced).

Array Declaration and Initialization


As other variables, a programmer has to declare an array before it can be used. It is declared using
the following format:

dataType arraName[intExp];
where intExp is any constant expression that evaluates to a positive integer. Also, intExp
specifies the number of components or elements in the array.
For example, the statement:

float number[5];
declares an array marks of five components. Each component is of type float. The components
are number[0], number[1], number[2], number[3], and number[4]. The following
diagram illustrates the array number.

number[0]

number[1]

number[2]

number[3]

number[4]

When declaring an array, a programmer has to ensure that the size of an array is enough to process
the required data.
A constant value may be used in declaration of an array as the following example.

const int SIZE = 20;


double speed[SIZE];
The value of an array may be initialized during declaration of the variables as the following examples:
int List[5] = {5, 7, 11, 13, 17};
int tally[6] = {4, 6, 2};
float score[100] = {0};
double sales[30] = {546.80};
int data[] = {3, 8, 1, 12, 0, 9, 11};
char letter[5] = {'Q', 'W', 'E', 'R', 'T'};
2

CSC138

Lecture Note

char name1[] = {"Anas Zuhair"};


char name2[] = "Ilma Adliyya";
char name3[40] = "Muhammad Ammar Mubin";

Accessing Elements of an array


The general form (syntax) used for accessing an array component is:

arraName[indexExp]
where indexExp, called the index, is any expression whose value is a non negative integer. The
index value specifies the position of the component in the array. In C++, the array index starts at 0.
Assume the following array is used.

int list[6] = {10, 32, 45, 67, 77, 98};


The following memory will be located.
list[0]
10

list[1]
32

list[2]
45

list[3]
67

list[4]
77

list[5]
98

An index (subscript) is used to access the value of elements in an array. list[0] is read as list
sub 0 or list index 0. list[0] refers to the value of the first item in the list or the first element in
the list or the first member in the list or the first location in the list.
The eight element is referred as list[7], not list[8] because index start from 0. list[8]
does not exist.
Sample statements, which are used to manipulate the element of this array:

Statements

Actions
Display the value of list sub 2, which
is 45.
Replace the value in list[3] with 65.
Store the sum of list sub 0 and list
sub 1 to variable sum
Add value of list sub 2 to sum
Store the sum of list sub 2 and list
sub 1 to list sub 4.
Display all value of elements in list

cout<< list[2];
list[3] = 65;
sum = list[0] + list[1];
sum = sum + list[2];
list[4] = list[2] + list[1];
for(i=0; i<6; i++)
cout<<list[i] << ;

CSC138

Lecture Note

Using a Loop Statement with an Array


One of the advantages of using an array is the ability to repeat the same statements to the other
elements of the same array. A loop structure is used to accomplish this task as the example below:
void main()
{
int listNum[10] = {10,20,30,40,50,60,70,80,90,100};
int ind;
cout<< "The contents of listNum : <<endl;
for(ind = 0; ind < 10; ind++)
cout << listNum[ind] << " ";
for(ind = 0; ind < 10; ind++)
listNum[ind] = listNum[ind] / 10;
cout << "\nThe contents of listNum after processing : "<<endl;

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


cout << listNum[ind] << " ";

Output of the program:

The contents of listNum :


10 20 30 40 50 60 70 80 90 100
The contents of listNum after processing :
1 2 3 4 5 6 7 8 9 10

Input and Output Elements of an Array


This example shows how loops are used to process arrays for input and output. The following
declaration is used throughout this example:

double sales[10];
int ind;
double highestSale, sum, average;
The first statement declares an array sales of 10 components, with each component being of type
double. The meaning of the other statements is clear.
a) Initializing an array: The following loop initialize every component of the array sales to 0.0.

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


sales[ind] = 0.0;
b) Reading data into an array: The following loop inputs the data into the array sales. For
simplicity, we assume that the data is entered at the keyboard.

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


cin >> sales[ind];

CSC138

Lecture Note

c) Printing an array: The following loop outputs the array sales. For simplicity, we assume that
the output goes to the screen.

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


cout << sales[ind] << ;
Array Operations
Arrays can also being used in operations of 7 basic algorithms (sum/total, average, count occurrences,
maximum, minimum, sorting and searching). The following declaration is used as an example to
explain the uses of array in 7 basic algorithms.
int size = 20
int number[size];
int highest, lowest, ind, countOdd;
float sum, average;
a) Finding the sum and average of an array: The following C++ code finds the sum of the
elements of the array number and the average of all numbers. Assume that the array already
has input data.

sum = 0;
for(ind = 0; ind < size; ind++)
sum = sum + number[ind];
average = sum / size;
cout<< Sum of all numbers : <<sum<<endl;
cout<< The average is : <<average<<endl;
b) Highest element in the array:

highest = 0;
for(ind = 0; ind < size; ind++)
{
if(number[ind] > highest)
highest = number[ind];
}
cout<< The highest value in array is : <<highest<<endl;
OR

highest = number[0];
for(ind = 1; ind < size; ind++)
{
if(number[ind] > highest)
highest = number[ind];
}
cout<< The highest value in array is : <<highest<<endl;

CSC138

Lecture Note

c) Lowest element in the array:

lowest = 9999;
for(ind = 0; ind < size; ind++)
{
if(number[ind] < lowest)
lowest = number[ind];
}
cout<< The lowest value in array is : <<lowest<<endl;
OR

lowest = number[0];
for(ind = 1; ind < size; ind++)
{
if(number[ind] < lowest)
lowest = number[ind];
}
cout<< The lowest value in array is : <<lowest<<endl;
d) Count the Occurrence: For example, count the number of odd numbers in the array.
countOdd = 0;
for(ind = 0; ind < size; ind++)
{
if(number[ind] % 2 == 1 )
countOdd = countOdd + 1; //or countOdd++
}
cout<< The number of odd numbers : <<countOdd<<endl;
e) Searching (Linear/Sequential Search)
Lets start with the problem statement for searching:
Given a value X, return the index of X in the array, if such X exists. Otherwise, return
NOT_FOUND (-1). We assume there are no duplicate entries in the array.
There are two possible outcomes in searching: Either we locate an X or we dont. We will call
the first a successful search and the latter an unsuccessful search. Figure below illustrates the
successful and unsuccessful searches. An obvious as this may sound, it is critical to
differentiate the two because it is possible for one searching algorithm to perform superbly for
successful searches, but very poorly for unsuccessful searches. When we analyze the
performance of a searching algorithm, we normally derive two separate performances, one for
a successful search and another for an unsuccessful search.
Unsuccessful search:

search(45) -- NOT_FOUND (-1)

Successful search:

search(12) -- 4

number
0

23

17

90

12

44

38

84

77

CSC138

Lecture Note

In a linear search we search the array from the first position to the last position in a linear
progression. The linear search is also called a sequential search. The linear search algorithm
can be expressed as:
int loc = 0;
int searchValue;
cout<< Enter the search value : ;
cin>>searchValue;
while (loc < size && number[loc] != searchValue)
{
loc++;
}
if(loc == size)
cout<< Sorry! The value not found. ;
else
cout<< The value stored at index : <<loc;
OR

f)

for(ind = 0; ind < size; ind++)


{
if(number[ind] == searchValue)
{
loc = ind;
break;
}
}
if(ind == size)
cout<< Sorry! The value not found. ;
else
cout<< The value stored at index : <<loc;

Sorting (Bubble sort)


Lets start with the problem statement for sorting:
Given an array of N values, arrange the values into ascending order.
The key point of the bubble sort is to make pair-wise comparisons and to exchange the
positions of the pair if they are out of order. The following figure shows the effect of pair-wise
comparisons in the first pass of the bubble sort. After the first pass, the largest element (in this
example, 90), has moved to its correct position in the array. This is the guaranteed effect of
one pass. In addition, we notice that many other elements have moved toward their correct
positions, as bubble move toward the waters surface.
In the worst case, the bubble sort will make N-1 passes, so the worth-case performance is the
same as the selection sort. However, in the average case, we can expect a better
performance from the bubble sort. The bubble sort exhibits two properties:
- After one pass through the array, the largest element will be at the end of the array.
- During one pass, if no pair of consecutive entries is out of order, then the array is sorted.
7

CSC138

Lecture Note

23

17

90

12

44

38

84

77

90

12

44

38

84

77

23

90

12

44

38

84

77

23

90

12

44

38

84

77

Exchange
0

17

23

2
5

Exchange

0
17

1
5

0
17

1
5

Exchange
0
17

1
5

23

12

90

44

38

84

77

38

84

77

84

77

Exchange
0
17

1
5

23

12

44

5
90

Exchange
0
17

1
5

23

12

44

38

90

Exchange
0
17

1
5

23

12

44

38

84

90

77

Exchange
0
17

1
5

23

12

44

38

84

77

90

Figure: Effect of executing the first pass in the bubble sort.

CSC138

Lecture Note

Using these properties, we can express the bubbleSort in the following algorithm:
int bottom, temp;
bool exchange = true;
bottom = size 2;
while(exchange)
{
exchange = false;
for(ind = 0; ind <= bottom; ind++)
{
if(number[ind] > number[ind+1])
{
temp = number[ind];
number[ind] = number[ind+1];
number[ind+1] = temp;
exchange = true;
}
}
bottom--;
}
for (ind = 0; ind < size; ind++)
cout << number[ind] << " ";
OR
for(int j = 1; j < size; j++)
{
for(int k = 0; k < (size-j); k++)
{
if (number[k] > number[k+1])
{
temp = number[k];
number[k] = number[k+1];
number[k+1] = temp;
}
}
}
for (ind = 0; ind < size; ind++)
cout << number[ind] << " ";

Array and Function


In C++, arrays are passed by 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 an array as a formal parameter, the size of the array is usually omitted. If you specify
the size of an array when it is declared as a formal parameter, the size is ignored by the compiler.

CSC138

Lecture Note

Consider the following function:

void funcArrayAsParam(int list[])


{
:
:
}
The function funcArrayAsParam has one formal parameter: list, an array of type int (that is, the
component type is int). In this declaration, the size of the array is unspecified. In order to pass to this
function an array declared as:

int theArray[20];
it would be enough to write a call like this:
funcArrayAsParam(theArray);
Sometimes, the number of elements in the array might be less than the size of the array. For example,
the number of elements in an array storing student data might increase or decrease as students drops
or add courses. In such situations, we want to process only the components of the array that holds
actual data. To write a function to process such arrays, in addition to declaring an array as a formal
parameter, we declare another formal parameter specifying the number of elements in the array, as in
the following function:

void displayArray(int list[], int size)


{
for(int i = 0; i < size; i++)
cout<<list[i] << ;
cout<<endl;
}
The first parameter of the function displayArray is an int array of any size . When the function
displayArray is called, the size of the actual array is passed as the second parameter (int
size) of the function displayArray.
Here you have a complete example:
#include<iostream>
using namespace std;
void displayArray(int [], int);
void main()
{
int array1[] = {3,9,12};
int array2[] = {6,7,8,9,11};
displayArray(array1,3);
displayArray(array2,5);
}
void displayArray(int list[], int size)
{
for(int i = 0; i < size; i++)
cout<<list[i] << ;
cout<<endl;
}

10

CSC138

Lecture Note

In the case above, the first parameter (int list[]) accepts any array whose elements are of type
int, whatever its length. For that reason, we have included a second parameter that tells the function
the length of each array that we pass to its first parameter. This allows the for loop that prints out the
array to know the range to iterate in the array passed, without going out of range.
In certain situation we may need to pass only one or two elements of an array to a function, not the
entire array. Although entire arrays are passed by reference, individual array elements are passed by
value or by reference exactly as simple variables are. To pass an element of an array to a function,
use the subscripted name of the array element as an argument (actual parameter) in the function call
and a variable without subscript as simple variable for formal parameter in the function definition
header.
Consider the following function definition:
void compare(int value1, int value2)
{
if(value1 > value2)
cout<< Highest : <<value1<<endl;
else
cout<< Highest : <<value2<<endl;
}
For example we have an array as follows:
int theArray[10] = {4,7,2,9,12,6,19,32,11,1};
In order to pass the third and fourth elements of that array, we can write a call for the above function
like this:
compare(theArray[2], theArray[3]);
When we pass individual array elements by value to a function, the content of the original array will
remain. If we want the changes made in the function effect the original array elements, we have to use
reference parameter as simple variable. The following example of function definition shows how to use
reference parameter.
void swap(int &value1, int &value2)
{
int temp;
if(value1 > value2)
{
temp = value1;
value1 = value2;
value2 = temp
}
}
We can make a function call statement as follows:
swap(theArray[i], theArray[i+1]);

11

Vous aimerez peut-être aussi