Tải bản đầy đủ (.ppt) (31 trang)

C++ lecture 15

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (375.48 KB, 31 trang )

C++ Programming
Lecture 15

Arrays
– Part II
The Hashemite
University
Computer Engineering
Department
(Adapted from the textbook slides)


Outline


Introduction.



Passing arrays to functions.



Sorting arrays.



Multisubscripted arrays.




Examples.

The Hashemite University

2


Introduction




In this lecture we will see how we can
deal with arrays as ordinary variables
and pass them to functions as parameters.
Also, we will examine algorithms to sort
the elements found in an array either in:





Ascending order.
Or descending order.

Finally, we will see how to create and
initilaize multi-dimensional arrays.

The Hashemite University


3


Passing Arrays to
Functions I


You can pass an array to a function
like any other variable with some
differences.






Function prototype: you must tell the compiler
that the passed parameter is an array.
Function call: just pass the name of the array
in the function call like any other variable.
Function definition: copy the prototype as the
function header and specify the names of the
variables.
The Hashemite University

4


Passing Arrays to
Functions II



Function prototype:
void modifyArray( int b[], int arraySize );



Parameter names optional in
prototype
int b[] could be simply int []

int arraysize could be simply int.

If the size of the array is passed
as, e.g. int b[5], the compiler
will ignore it.


The Hashemite University

5


Passing Arrays to
Functions III


Function Call:



Specify the name without any
brackets


To pass array myArray declared as

int myArray[ 24 ];
to function myFunction, a function call would
resemble

myFunction( myArray, 24 );


Array size is usually passed to the function to
allow correct processing of the array elements.

The Hashemite University

6


Passing Arrays to
Functions IV


Arrays are passed as call-by-reference by
default




Value of name of array is address of the first element
Function knows where the array is stored




Modifies original memory locations

Individual array elements are passed by callby-value
pass subscripted name (i.e., myArray[ 3 ]) to function
 If you want to pass an element by reference then you must use
reference variables.
To prevent a function from modifying an array declare the
parameter array within both the function definition and
the function prototype as a const (i.e. pass it as readonly variable). So, any modification will be reported as
a syntax error.




The Hashemite University

7


Calling array by value and
by reference (1)
void modify (int [] );
int main()
{

int array1[4]={2,4,6,8};
modify(array1);
cout<<"first element "<cout<<"first element "<cout<<"first element "<cout<<"first element "<return 0;
}
void modify (int array[])
{
for (int i=0;i<3;i++)
array[i]*=2; //arra[i]=array[i]*2
array[3]+=20;
}
The Hashemite University

8


Calling array by value and
by reference (1)
void modify (int, int, int, int & );
int main()
{
int array1[4]={2,4,6,8};
modify(array1[0], array1[1],
array1[2], array1[3]);
cout<<"first element
"<cout<<"first element

"<cout<<"first element
"<cout<<"first element
"<return 0;
}
void modify (int a,int b,int c,int &d)
{
a*=2; b*=2;c*=2;d=100;
The Hashemite University
}

9


1 // Fig. 4.14: fig04_14.cpp
2 // Passing arrays and individual array elements to
functions
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
Functions can modify entire
8 #include <iomanip>
arrays. Individual array
9
elements are not modified by
10 using std::setw;

default.
11
12 void modifyArray( int [], int ); // appears strange
13 void modifyElement( int );
14
No parameter names in
15 int main()
function prototype.
16 {
17
const int arraySize = 5;
18
int i, a[ arraySize ] = { 0, 1, 2, 3, 4 };
19
20
cout << "Effects of passing entire array call-byreference:"
21
<< "\n\nThe values of the original array are:\n";
22
23
for ( i = 0; i < arraySize; i++ ) The values of the original array are:
24
cout << setw( 3 ) << a[ i ];
0 1 2 3 4
25
The values of the modified array are:
26
cout << endl;
27
0 2 4 6 8

28
// array a passed call-by-reference
29
modifyArray( a, arraySize );
The Hashemite University
30

10


32
33
for ( i = 0; i < arraySize; i++ )
34
cout << setw( 3 ) << a[ i ];
35
36
cout << "\n\n\n"
37
<< "Effects of passing array element call-byvalue:"
38
<< "\n\nThe value of a[3] is " << a[ 3 ] << '\n';
39
40
modifyElement( a[ 3 ] );
41
42
cout << "The value of a[3] is " << a[ 3 ] << endl;
43
Parameter names required in function

44
return 0;
definition
45 }
46
47 // In function modifyArray, "b" points to the original
48 // array "a" in memory.
49 void modifyArray( int b[], int sizeOfArray )
50 {
Effects of passing array element call-by-value:
51
for ( int j = 0; j < sizeOfArray; j++ )
 
52
b[ j ] *= 2;
The value of a[3] is 6
53 }
Value in modifyElement is 12
54
55 // In function modifyElement, "e" is aThe
local
of is 6
valuecopy
of a[3]
56 // array element a[ 3 ] passed from main.
57 void modifyElement( int e )
58 {
59
cout << "Value in modifyElement is "
The Hashemite University

11
60
<< ( e *= 2 ) << endl;
61 }


Effects of passing entire array call-by-reference:
 
The values of the original array are:
0 1 2 3 4
The values of the modified array are:
0 2 4 6 8
 
 
Effects of passing array element call-by-value:
 
The value of a[3] is 6
Value in modifyElement is 12
The value of a[3] is 6

Program Output

The Hashemite University

12


Sorting Arrays I



Sorting data



Important computing application
Virtually every organization must sort some data




Massive amounts must be sorted

Bubble sort (sinking sort)




Ar[6]={-1,4,5,0,11,4}

Ascending order.
Several passes through the array
Successive pairs of elements are compared





How to bubble sort

If increasing order (or identical), no change

If decreasing order, elements exchanged

Repeat these steps for every element
The Hashemite University

13


Sorting Arrays II


Example:







Why we need a number of passes equal
to arraySize – 1?




Original: 3 4 2 6 7
Pass 1:
3 2 4 6 7
Pass 2:
2 3 4 6 7

Small elements "bubble" to the top

Since in the worst case the smallest value may
reside on the last element within the array. At each
pass this element move one step toward the top of
the array.

Disadvantages:


Slow for large size arrays (large number of passes is
required).
The Hashemite University

14


Bubble Sorting Code


Found as a part within the next example, also
will be written on the board.



See how you can modify the code that we have
write (also found in the textbook) to sort the
array in a descending order.

The Hashemite University


15


Multiple-Subscripted
Arrays I


Multiple subscripts - tables with rows, columns


 

Like matrices: specify row, then column.
Row 0

Column 0
a[ 0 ][ 0 ]

Column 1
a[ 0 ][ 1 ]

Column 2
a[ 0 ][ 2 ]

Column 3
a[ 0 ][ 3 ]

Row 1


a[ 1 ][ 0 ]

a[ 1 ][ 1 ]

a[ 1 ][ 2 ]

a[ 1 ][ 3 ]

Row 2

a[ 2 ][ 0 ]

a[ 2 ][ 1 ]

a[ 2 ][ 2 ]

a[ 2 ][ 3 ]

Column subscript
Array name
Row subscript

The Hashemite University

16


Multiple-Subscripted
Arrays II



Referenced like normal
cout << b[ 0 ][ 1 ];



Will output the value of 0
Cannot reference with commas
cout << b( 0, 1 );


Will try to call function b, causing a syntax error

The Hashemite University

17


Multiple-Subscripted
Arrays III


Initialization:




Using two nested for loops.
Using cin to get values from the keyboard.
Using initializers list: Initializers grouped

by row in braces
1
2
int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };

The Hashemite University

3

4

1

0

3

4

18


int main()
{
int t[2][3];
for(int i=0;i<3;i++)
{
for(int j=0;j<2;j++)
{

t[j][i]=i+1;
}
}

How does it work
?
t[0][0]=i+1=1
t[1][0]=i+1=1
t[0][1]=i+1=2
t[1][1]=i+1=2
t[0][2]=i+1=3
t[1][2]=i+1=3

0
1

0

1

2

1
1

2
2

3
3


The Hashemite University

19


Notes I
1- If you declare an array (onesubscript or
multisubscript) and don’t initialize it the
elements will have garbage numbers
int array[5] , array1[2][2];
cout<-858993460

2- If you declare an array (onesubscript or
multisubscript) and initialize some elements and
leave the others uninitialized , the
uninitialized elements will be given the value 0
if it is a integer array and assigned a space if
it is an character array.
int array[5]={1} , array1[2][2]={{12},{3}};
cout<print 0 0 0
The Hashemite University

20


Notes II
3- If you try to fill a location (using

initializer list) that is outside the
array boundary syntax error will be
generated
int array1[2][2]={{12},{3},{4}};
error because the array

//syntax
has only

two rows and you try to

fill the third row by {4}

The Hashemite University

21


Multiple-Subscripted
Arrays IV


Try the following on your computer and
see what is the results of the
following initializations and whether
there is a syntax error or not.













int
int
int
int
int
int
int
int
int

b[ 2 ][ 2 ] = { 1, 2, 5 }; //Correct
b[][] = {{1,3},{5},{6,7,8}}; //Syntax Error
b[ 2 ][] = { 1, 2, 5 };//Syntax Error
b[][ 2 ] = { 1, 2, 5 }; //Correct
b[][ 2 ][4] = { 1, 2, 5 }; //Correct
b[][ 2 ][] = { 1, 2, 5 }; // Syntax Error
b[][] = { 1, 2, 5 };//Syntax Error
b[][3] = {{-1,1,2,4}}; // syntax error
b[][3] = {{-1,1,2},{4}}; // correct

Note that only the first subscript (or dimension size) is
allowed to be empty.

The Hashemite University

22


Case Study: Computing Mean,
Median and Mode Using Arrays


Mean




Median





Average
Number in middle of sorted list
1, 2, 3, 4, 5 (3 is median)

Mode



Number that occurs most often
1, 1, 1, 2, 3, 3, 4, 5 (1 is mode)

The Hashemite University

23


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

26
27
28
29
30
31
32
33

// Fig. 4.17: fig04_17.cpp
// This program introduces the topic of survey data analysis.
// It computes the mean, median, and mode of the data.
#include <iostream>
using std::cout;
using std::endl;
using std::ios;
#include <iomanip>
using std::setw;
using std::setiosflags;
using std::setprecision;
void
void
void
void
void

mean( const int [], int );
median( int [], int );
mode( int [], int [], int );
bubbleSort( int[], int );

printArray( const int[], int );

int main()
{
const int responseSize = 99;
int frequency[ 10 ] = { 0 },
response[ responseSize ] =
{ 6, 7, 8, 9, 8, 7, 8, 9,
7, 8, 9, 5, 9, 8, 7, 8,
6, 7, 8, 9, 3, 9, 8, 7,
7, 8, 9, 8, 9, 8, 9, 7,
6, 7, 8, 7, 8, 7, 9, 8,
7, 8, 9, 8, 9, 8, 9, 7,
5, 6, 7, 2, 5, 3, 9, 4,

8,
7,
8,
8,
9,
5,
6,

9,
8,
7,
9,
2,
The
3, Hashemite University

4,

24


34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58

59
60
61
62
63
64
65
66
67

7, 8, 9, 6, 8, 7, 8, 9, 7, 8,
7, 4, 4, 2, 5, 3, 8, 7, 5, 6,
4, 5, 6, 1, 6, 5, 7, 8, 7 };
mean( response, responseSize );
median( response, responseSize );
mode( frequency, response, responseSize );
return 0;
}
void mean( const int answer[], int arraySize )
{
int total = 0;
cout << "********\n

Mean\n********\n";

for ( int j = 0; j < arraySize; j++ )
total += answer[ j ];
cout <<
<<
<<

<<
<<
<<
<<
<<
<<

"The mean is the average value of the data\n"
"items. The mean is equal to the total of\n"
"all the data items divided by the number\n"
"of data items (" << arraySize
"). The mean value for\nthis run is: "
total << " / " << arraySize << " = "
setiosflags( ios::fixed | ios::showpoint )
setprecision( 4 )
static_cast< double >( total ) / arraySize << "\n\n";

}
void median( int answer[], int size )
The Hashemite University
{
cout << "\n********\n Median\n********\n"

25


Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×