78
Arrays Structured Programming 256 Chapter 10

Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

Embed Size (px)

Citation preview

Page 1: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

Arrays

Structured Programming 256

Chapter 10

Page 2: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Arrays

One-Dimensionalinitialize & display

Arrays as Arguments

Two-dimensional initialize & display

Part I

Page 3: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Data Types

a simple or atomic

a structured

* *

char, int, float, double

array, struct, union, class

Page 4: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Structured Data Type - Array

• An array is a collection of data storage locations, each of which holds the same type of data. Each storage location is called an element of the array.

• Each element is referred to as an indexed or subscripted variable.

Page 5: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Array Declaration

• SyntaxdataType arrayName [[ ConstIntExpression ]]

• The number of elements in an array is • stated within square brackets, [ ][ ].

• Examplesdouble angle [4]; constant POLY = 8;int testScore [12]; double angle [POLY]; char password [8];

Page 6: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Array Storage

• Each array has sufficient memory reserved to hold the number of data items of the given type.

• Initializing an array sets up the address of the first element. Addresses of all other elements are offsets from the starting address.

Page 7: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Array Element Access

• Syntax• arrayName [ indexExpression ]

• Program access to each of the array elements is by referring to an offset from the array name. Array elements are counted beginning with zero.

Page 8: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Array Element Access

• double angle[4]; // declaration

• Exampleangle [0] = 6.21;angle [1] = 15.89;angle [2] = 7.5;angle [3] = -45.7;

angle sub zero = 6.21angle sub one = 15.89angle sub two = 7.5angle sub three = -45.7

* * *

Page 9: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Using Array Elementsa write the contents of an array element:

cout << angle[2];

a assign values to an array element:cin >> angle[3];angle[6] = pow(axis,4);

a use it as a parameter:y = sqrt(angle[0]);

a use it in an expression:x = 2.5 * angle[1] + 64;

* * * *

Page 10: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Array Component Access

• for(indexindex=0; index index < arraySize; indexindex++)myArray[indexindex] = 0.0;

100

* *

Zero out an entire array. (Initialize every element to 0.0.)

Page 11: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Off Set• memory

addresses

• starting address

• off set by one unit

• off set by two units

• off set by three units

[ 0 ]

[ 1 ]

[ 2 ]

[ 3]

@#$

@#$

Page 12: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Out-of-Bounds Array Index• memory

addresses

• angle[4] = 135;

cout << angle[5];

[ 0 ]

[ 1 ]

[ 2 ]

[ 3]

@#$

@#$

Page 13: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Declare an Array

• Syntaxtype arrayName[index];

Exampledouble dailyHigh[23] ;

int quizGrade[132] ;

char ASURiteID[5] ;

*

Page 14: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Initialize an Array Element

• SyntaxarrayName[index] = value;

ExampledailyHigh[18] = 16.7;

quizGrade[2] = 15;

ASURiteID[3] = ‘d’;

*

Page 15: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Initialize an Array

double angle[4] = {16.21, 15.89, 7.5, -45.7};

double ATtoCG[5] = {.64, .89, .76, .83, .65};

int scores[12] = {210, 198, 203, 188, 200, 224, 220, 217, 211, 194, 197, 189};

double iona[8] = {0.0};*

Page 16: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Initialize an Array

int scores[ ] = {210, 198, 203, 188, 200, 224, 220, 217, 211, 194, 197, 189};

char name[4] = {‘Z’, ‘o’, ‘l’, ‘a’};

char name[4] = “Zola”; // no braces or ,char phrase [ ] = “Hello World”;

* *

Page 17: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Initialize an Array

double angle[4]; // declaration

Exampleangle [0] = 6.21;angle [1] = 15.89;angle [2] = 7.5;angle [3] = -45.7;

angle sub zero = 6.21angle sub one = 15.89angle sub two = 7.5angle sub three = -45.7

*

Page 18: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Sequencing Through an Array

• Use the for statement to sequence through an array.

• Total the contents of an array:sum = 0;for(index=0; index < 7; index++)

sum = sum + grades[index];

Page 19: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Loading an Array

• double grade[10];

• int index;

• for(index=0; index < 10; index++){

cout<<“Enter a grade “;

• cin >> grade[index];

• }

Page 20: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Finding the Max/Min Value

• Set the max or min to element zero.

• Use a for loop to cycle through the array.

• Compare each element to the max/min.

• If necessary, assign a new value to max/min.

How would you do this?

*

Page 21: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Finding the Maximum Value

• double find_max(int temp[30])• {• max = temp[0];

• for(index=0; index < 30; index++)if (temp[index] > max)

max = temp[index];• return (max);• }

*

Page 22: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Finding the Minimum Value

• double find_min(int temp[30])• {

• min = temp[0];

• for(index = 1; index < 30; index++)if (temp[index] << min)

min = temp[index];• return ( min );• }

*

Page 23: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Aggregate Assignment - NOT!

• There are no aggregate assignments with arrays. That is, you may not assign one array to another.

• int x[5] = {11, 22, 33, 44, 55};

• int y[5];

• y = x; y[ ] = x[ ];

Page 24: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Arrays as Arguments

• void find_max(int temp[ ]temp[ ])• {

• max = temp[0];

• for(index = 1; index < 30; index++)if (temp[index] > max)

max = temp[index];

• }

double find_max(int temp[ ]temp[ ])

*

return max;

Page 25: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Passing an Array/Element

• find_max(temptemp); // no [ ]

• inventory(priceprice, quantityquantity, amountamount); // 3 arrays

• words(cupletcuplet);

find_max(temp[3]temp[3]); inventory(priceprice, quantity[4]quantity[4], amount[12]amount[12]);words(cupletcuplet);

*

Page 26: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Passing an Array

• formal parameterformal parameter formal parameterformal parameterdeclaration fordeclaration for declaration fordeclaration for

parameterparameter Pass-by-ValuePass-by-Value Pass-by-ReferencePass-by-Reference

•simple var. int cost int& pricearray impossible int myArray[ ]

•array const int source[ ]

Page 27: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

1-D Array Review• An array is a structured data type• 1st element is “arrayName subzero”

• Array Declarationint myArray [9];

• Array Initializationint myArray [9 ] = { 9, 9, 9, 8, 7, 6, 5, 4,

3};

• Array Element ReferencemyArray [7]; // value = 4 *

99

Page 28: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

1-D Array Review• Arrays are always passed by reference, unless

const added to the formal parameter.

• Array in a Function Prototype• void myFunction(int [9]);

• Array in a Function CallmyFunction(myArray);

• Array in a Function Headervoid myFunction(int anyArrayName[9])

optional

Page 29: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Two Dimensional Arrays

a everything about one dimensional arrays applies

a sometimes referred to as a table

a has rows and columnsex. multiplication table

Page 30: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

2-D Array Declaration• Syntax• dataType arrayName [[ ConstIntExpression ]]

[[ ConstIntExpression ]]

• Example• int highTemp [52] [7];

double matrix [8] [8]; // checker boardint roomSchedule [237] [13];

Page 31: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

2-D Array Initialization

• int nums [3] [2] = {7, 4, 1, 8, 5, 2}

• int roomsPSF[3] [7] = { {17, 18,19, 110, 111, 112, 113},

{27, 28, 29, 210, 211,212, 213},{37, 38, 39, 310, 311, 312, 313} };

Page 32: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

2-D Array Initialization

• double ATtoCG[2] [3] = {.74, .79, .76, .83, .65, .89};

• double ATtoCG[2] [3] = { {.74, .79, .76}},

{.83, .65, .89} };

• int scores[4] [3] = {210, 198, 203, 188, 200, 224, 220, 217, 211, 194, 197, 189};

Page 33: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

2-D Array Initialization

• You can assign values to individual elements:

• ATtoGC [0] [0] = 0.74;

ATtoGC [0] [1] = 0.79;

ATtoGC [0] [2] = 0.76;

ATtoGC [1] [0] = 0.83;

ATtoGC [1] [1] = 0.65;

*

ATtoCG [1] [2] = 0.89;

Page 34: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Accessing a 2-D Array

a very similar to creating a multiplication table.

a use nested loops.outer for loop was for the rowsinner for loop was for the columns

Page 35: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Loading a 2-D Array

a The Multiplication Table

• for (row =1; row <=10; row++)• {• cout <<setw(5)<<row<<" ";• forfor (column=1; column <= 10;

column++)• cout << setw(5)<< column*row;• cout << endl;• }

Page 36: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Loading a 2-D Array

• int scores [4][3];

• for(row=0; row<4; row++)• for(col=0; col<3; col++)• {• cout<<"Enter the value :";• cin>>scores[row][col];• }

Page 37: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Loading a 2-D Array

• scores [0][0] [2][0] [0][1] [2][1] [0][2] [2][2]

• [1][0] [3][0] [1][1] [3][1] [1][2] [3][2]

[row][col] = somevalue;

Page 38: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Displaying a 2-D Array• int scores [4] [3];

• for(row=0; row<4; row++)• {• for(col=0; col<3; col++)• cout << setw(6) << scores[row][col];• cout << endl; // new line for each row• }

Page 39: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Displaying a 2-D Array

• Output• 210 198 203

188 200 224220 217 211194 197 189

Page 40: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Functions and 2-D Arrays

• int test[7][19]; // declaration

• find_min(test); // function call

• int find_min(int num [7][19]) // funct. header

* * * *

char code[26][10];char code[26][10];

obtain(code);obtain(code);

char obtain(char key [26][10])char obtain(char key [26][10])

Page 41: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Local vs. Global

• No difference

Page 42: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Arrays

Multi-dimensional initialize & display

Sorting

Part II

Page 43: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Multidimensional Arrays

a everything about one dimensional arrays applies

a all elements of the same data type

a just need additional sets of [ ][ ]

a a 3-D array has rows, columns, and rank

Page 44: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Multidimensional Arrays• int scores [4] [3] [2]; // assume loaded with 1-24

• for(row=0; row<4; row++)• {• for(col=0; col<3; col++)• {• for(rank=0; rank<2; rank++)• cout<<setw(6)<<scores[row][col][rank];• cout<<endl; // new line for each row• }

Page 45: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Multidimensional Arrays

• {• cout <<endl; // start a new line• • { •• cout<<setw(6)<<nums[row][col][rank]nums[row][col][rank];• cout<<endl;// start a new line• }• }

for(rank=0; rank < 2; rank++)

for(col=0; col < 3; col++)

for(row=0; row < 4; row++)

Page 46: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

A

B

C

D

E

28

40

29

9

14

• parallel arrays = two or more arrays in which elements with corresponding indexes are related

Parallel Arrays

Used when related data is of different data types.grade % of class

*

Page 47: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Parallel Arrays

• for(row…

• for(col…{ cout >> “Enter id#”;

cin >> id[row][col];

• cout >> “Enter grade”;cin >> grade[row][col];

}

Page 48: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Sum a Row• void main(void)• {• double nums [3][4] = {1, 2, 3, 4, 5, 6, 7, 8,

9, 10, 11, 12};• double sumRow(double [3] [4]); // prototype•• cout << “The sum of row 3 is “• << sumRow(nums)<<endl; //function

call• }

Page 49: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Sum a Row• double sumRow(double ary[3][4])

{ int col; double total=0;

for(col = 0; col < 4; col++)total += ary[ ][col];

return total;}

* *

total += ary[2][col]; //enter row #-1

output The sum of row 3 is 42The sum of row 3 is 42

Page 50: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Sum a Column• void main(void)• {• double nums [3][4] = {1, 2, 33, 4, 5, 6, 77, 8,

9, 10, 1111, 12};• double sumCol(double [3] [4]); // prototype•• cout << “The sum of column 3 is “• << sumCol(nums) << endl; //function

call• }

Page 51: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Sum a Column• double sumCol(double ary[3][4])

{ int row; double total=0;

• for(row = 0; row<3; row++)total += ary[row][ ];

return total;}

*

total += ary[row][2]; //enter col #-1

output The sum of column 3 is 21The sum of column 3 is 21

Page 52: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Sum All Rows• void sumRow(double ary[3][4])

{ int row, col;double total=0;

for(row = 0; row < 3; row++) { total = 0; // each row total begins at 0

for(col = 0; col<4; col++)total += ary[row][col]; // enter row #

cout << "The sum of row "<<row+1 << " is "<<total<<endl;

}cout<<endl;

}}

*

1

X

Page 53: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Sum All Columns• void sumCol(double ary[3][4])

{ int row, col;double total=0;

• for(col = 0; col < 4; col++){

total = 0; // each col. total begins at 0 for(row = 0; row < 3; row++)

total += ary[row][col]; //enter col #cout << "The sum of col " << col+1 << " is " << total << endl;

}}• cout<<endl;

}}*

1 3

X X

Page 54: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

• Just for fun!• A 2-D array has the same number of rows as

col.

• 1. How to sum the diagonals - upper left to lower right?

• 2. How to sum the diagonals - upper right to lower left?

Sum Each Diagonal

Page 55: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Sorting

• Internal Sorts [for small data sets]selectionbubble (exchange)

• External Sorts [for large data sets]

Page 56: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Selection Sort

index (k) sm_index

0 2swap 21, 9

1 1swap 13, 13

2 3swap 21, 15

3 4swap 21, 17

21 159 13 17

15 179 13 21

99 152121 13 17

15 21219 13 1717

2121 15159 13 17

Page 57: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Selection Sort

• void sort(double [5]);• void swap(double [5], int, int); // prototypes

• void main(void)• { int index;• double my_list[ ] = {21, 13, 9, 15, 17};

• sort(my_list); // function call

• cout<<"\nThe sorted array is: \n";• for(index=0; index<5; index++)• cout<<'\t'<<my_list[index]<<endl;• }

Page 58: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Selection Sort• void sort(double testArray[5])• { int n, k, sm_index, moves=0; double smallest;•• for(k=0; k<4; k++) // size-1 = number of passes• { smallest=testArray[k];• sm_index=k;• for(n=k+1; n<5; n++) // size = # elem. to look at• if(testArray[n]<smallest)• { smallest=testArray[n];• sm_index=n;• }• swap(testArray, sm_index, k); // call to

swap()• }• }

Page 59: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Selection Sort• void swap(double testArray[5], int smaller, int pass)• { // pass = current

position: k• int moves;• double temp;

• temp=testArray[pass];• testArray[pass]=testArray[smaller];• testArray[smaller]=temp;

• moves++; // not needed for swap• }

Page 60: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Bubble Sort

• Put smaller first

• Put smaller first

• No change

• Put smaller first21 252513 9 1717

2121 252513 9 17

99 252121 13 17

9 2513 21 17

Page 61: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Bubble Sort

• Begin again and put smaller first

• No change

• Put smaller first

21 179 13 25

17 21219 13 2525

2121 171313 9 25

2121 17179 13 25

Page 62: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

A Bubble Sort Function• void bubble_sort(int array[ ], int length)• {• int j, k, flag=1, temp;• for(j=1; j<=length && flag; j++)• {• flag=0; // false• for(k=0; k < (length-j); k++)• {• if (array[k+1] > array[k]) // > low to high• {• temp=array[k+1]; // swap• array[k+1]= array[k];• array[k]=temp;• flag=1; // indicates a swap• }} }} }} }} // has

occurred

Page 63: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Array Reviewa is an ordered sequence of data

of the same type

a can be of any valid data type

a can be 1-, 2-, or multi- dimensional

a must be declared before used

a can be assigned and initialized

a element numbering starts at zero

Page 64: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Array Review

a use for loops to access (nested for multidimentional)

a can be passed back and forth between functions

a when sent to functions the actual values are manipulated - not a copy

• (passed by reference)

Page 65: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Array Review -1 • Write a C++ program that adds equivalent

elements of the two-dimensional arrays named first and second. Both arrays should have two rows and three columns. For example, element [1][2] of the resulting array should be the sum of first[1][2] and second[1][2].

first second16 18 23 24 52 7754 91 11 16 19 59

sum40 70 10070 110 70

*

Page 66: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

• Write a C++ program that finds and displays the maximum value in a two-dimensional array of integers. It should also show the maximum value’s subscripts. The array should be declared as a four-by-five array of integers and initialized.

• data: 16, 22, 99, 4, 18, -258, 4, 101, 5, 98,• 105, 6, 15, 2, 45, 33, 88, 72, 46, 3

Array Review - 2

Page 67: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Array Review - 3

• Write a program which picks the elements in ascending order from a two dimensional matrix (4 by 5) and puts them in a single dimensional array. Display the single dimensional array.

Page 68: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

• There is a 3 by 5 array of grades. Write a program which reads the 15 grades and displays the number of grades below 60, number of grades in the 60's, number or grades in the 70's, number of grades in the 80's, and number of grades 90 or better.

Array Review - 4

Page 69: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

• Write a program that finds and displays the maximum value and its indicies in a two-dimensional array of integers. The array should be declared as a 10-row by 20-column array of integers in main().

Array Review - 5

Page 70: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Array Review - 6a

• There is an array of three students each with four exam scores. Assume the scores are known and are: {77, 68, 86, 73}, {96, 87, 89, 78}, {70, 90, 86, 81}. Create a program which will display the lowest grade, the highest grade and the average of the grades to two decimal places.

Page 71: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Array Review - 6b• #include <iostream.h>• #include <iomanip.h>

• const int STUDENTS = 3;• const int EXAMS = 4;

• int mini (int [][EXAMS], int, int);• int maxi (int [][EXAMS], int, int);• float average(int [], int);• void printArray(int [][EXAMS], int, int);

Page 72: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

Array Review - 6c• void main(void)• { int studentGrades[STUDENTS][EXAMS] = • {{77, 68, 86, 73}, {96, 87, 89, 78}, {70, 90, 86, 81}};

• cout << "The array is:" << endl;• printArray(studentGrades, STUDENTS, EXAMS);• cout<<endl<<endl<<"Lowest grade: "• << mini (studentGrades, STUDENTS, EXAMS)• << endl << "Highest grade: " • << maxi (studentGrades, STUDENTS,

EXAMS)<<endl;

• for (int person = 0; person < STUDENTS; person++)• cout << "The average grade for student " << person << " is " • <<setiosflags(ios::fixed | ios::showpoint)<<setprecision(2) • << average(studentGrades[person], EXAMS) << endl;• }

Page 73: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Array Review - 6d• int mini(int grades[][EXAMS],• int pupils, int

tests)• { • int lowGrade = 100;• for (int i = 0; i < pupils; i++)• for (int j = 0; j < tests; j++)• if (grades[i][j] < lowGrade)• lowGrade = grades[i][j];• return lowGrade; • }

int maxi(int grades[][EXAMS], int pupils, int tests)

{ int highGrade = 0; for (int i = 0; i < pupils; i++) for (int j = 0; j < tests; j++) if (grades[i][j] > highGrade) highGrade = grades[i][j]; return highGrade; }

Page 74: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Array Review - 6e• float average(int

setOfGrades[],• int tests)• { • int total = 0;• for (int i = 0; i < tests; i++)• total += setOfGrades[i];• return (float) total / tests; • }

void prtArray(int grades[][EXAMS], int pupils, int tests){ cout << " [0] [1] [2] [3]"; for (int i = 0; i < pupils; i++) { cout << endl<< "studentGrades["

<< i << "] ";

for (int j = 0; j < tests; j++) cout << setiosflags(ios::left)

<< setw(5) << grades[i][j];}

Page 75: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Array Review - 6f• function call:• average(studentGrades[person],

EXAMS)

• float average(int setOfGrades[], int tests)• { int total = 0;

• for (int i = 0; i < tests; i++)• total += setOfGrades[i];

• return total• }

Page 76: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Common Errors

Not declaring the arrayNot declaring the array First element is called First element is called zerozero; last element ; last element

is one less than the number of elementsis one less than the number of elements Out of rangeOut of range subscripts - no warning subscripts - no warning Error in the Error in the forfor loop - check the counter loop - check the counter Not initializing the arrayNot initializing the array

Page 77: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Common Errors

Aggregate operations not allowedAggregate operations not allowed Omitting array size - permitted only Omitting array size - permitted only

when declared as a formal parameter when declared as a formal parameter initialized in the declarationinitialized in the declaration

If array is /* in */ only, declare the If array is /* in */ only, declare the formal parameter as formal parameter as constconst to prevent to prevent accidental modificationaccidental modification

Page 78: Arrays Structured Programming 256 Chapter 10 © 2000 Scott S Albert Arrays One-Dimensional initialize & display Arrays as Arguments Two-dimensional initialize

© 2000 Scott S Albert

Debugging

array subscriptsarray subscripts

recheck array size in declaration, recheck array size in declaration, initialization, and initialization, and forfor loops loops

Prevention - plan first!Prevention - plan first!Valuation tablesValuation tablesDisplay values with coutDisplay values with cout