copyright © 2008 pearson addison-wesley. all rights reserved. chapter 7 arrays

153

Upload: joleen-ryan

Post on 18-Jan-2016

218 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays
Page 2: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Chapter 7

Arrays

Page 3: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 3

Overview

7.1 Introduction to Arrays

7.2 Arrays in Functions

7.3 Programming with Arrays

7.4 Multidimensional Arrays

Page 4: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

7.1

Introduction to Arrays

Page 5: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 5

Introduction to Arrays

An array is used to process a collection of dataof the same type Examples: A list of names

A list of temperatures Why do we need arrays?

Imagine keeping track of 5 test scores, or 100, or 1000 in memory

How would you name all the variables? How would you process each of the variables?

Page 6: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 6

Declaring an Array

An array, named score, containing five variablesof type int can be declared as int score[ 5 ];

This is like declaring 5 variables of type int:score[0], score[1], … , score[4]

The value in brackets is called A subscript An index

Page 7: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 7

The Array Variables

The variables making up the array are referred to as Indexed variables Subscripted variables Elements of the array

The number of indexed variables in an array isthe declared size, or size, of the array The largest index is one less than the size The first index value is zero

Page 8: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 8

Array Variable Types

An array can have indexed variables of any type

All indexed variables in an array are of thesame type This is the base type of the array

An indexed variable can be used anywhere an ordinary variable of the base type is used

Page 9: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 9

Using [ ] With Arrays

In an array declaration, [ ]'s enclose the sizeof the array such as this array of 5 integers:

int score [5]; When referring to one of the indexed variables,

the [ ]'s enclose a number identifying one of the indexed variables score[3] is one of the indexed variables The value in the [ ]'s can be any expression that

evaluates to one of the integers 0 to (size -1)

Page 10: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 10

Indexed Variable Assignment

To assign a value to an indexed variable, use the assignment operator: int n = 2; score[n + 1] = 99; In this example, variable score[3] is assigned

99

Page 11: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Array type and size

Type arrrayname[size of array] int first_array[5];

Slide 7- 11

Page 12: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Index

first_array [index] first_array [2]=79; Index[2]= 3 cout<< first_array [2]; float first_array[5];

Slide 7- 12

Page 13: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

int first_array[5]={34,26,43,23,54};

Slide 7- 13

Page 14: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Print array using Cin

#include<iostream.h> //decreasing . for (i=5;i>=0;i--)

main()

{ int i,first_arry[6];

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

cin>> first_arry[i] ;

cout<<"the Content of array is .\n";

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

cout<< first_arry[i]<<"\t";

system("pause");

return 0;

}

Slide 7- 14

Page 15: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Adding item in array #include<iostream.h> main() { int i,array1[5],sum=0; for (i=0;i<5;i++) cin>> array1[i] ; for (i=0;i<5;i++) sum=sum+array1[i]; cout<< "sum of array item="<<sum; system("pause"); return 0; }

Slide 7- 15

Page 16: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Adding array

Slide 7- 16

Page 17: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Find max number

#include<iostream.h> main() { int i,array1[7],max; for (i=0;i<7;i++) cin>> array1[i] ; max=array1[0]; for (i=0;i<7;i++) if (array1[i] > max ) max=array1[i]; cout<< "max number in array1 is="<<max;}

Slide 7- 17

Page 18: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Multiply by *2 array1[i]=2* array1[i]; //Multiply by *2 array1[i]= array1[i] /4; //divided by 4 #include<iostream.h> main() { int i,array1[5]={10,15,30,32,21}; for (i=0;i<5;i++) { array1[i]= array1[i]+5; cout<< array1[i]<<"\t";} }

Slide 7- 18

Page 19: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

int item; Item= first_arry[5]; first_arry[5]= first_arry[2]; first_arry[2]=item;

Slide 7- 19

Page 20: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Adding array of five item

#include<iostream.h>

main()

{ int i,array1[5],sum=0;

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

cin>> array1[i] ;

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

sum=sum+array1[i];

cout<< "sum of array item="<<sum;}

Slide 7- 20

Page 21: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

//Inter 7 item find maximum number

#include<iostream.h>

main()

{ int i,array1[7],max;

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

cin>> array1[i] ;

max=array1[0];

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

if (array1[i] > max )

max=array1[i];

cout<< "max number in array1 is="<<max;}

Slide 7- 21

Page 22: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Adding number to each array[i]

#include<iostream.h> main() { int i,array1[5]={10,15,30,32,21}; for (i=0;i<5;i++) { array1[i]= array1[i]+5; cout<< array1[i]<<"\t";} }

Slide 7- 22

Page 23: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Inter the number and sort by smaller to bigger #include<iostream.h>

int main()

{ int array[5],i,j;

int item=0;

cout<<"Here is the Array before sorted enter it\n";

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

cin>>array[i] ;

for ( i=0;i<5-1;i++)

for ( j=i; j<5;j++)

if (array[j] <array[i]) {

item =array[j];

array[j]=array[i];

array[i]= item ; }

cout<<"Here is the Array after sorted\n";

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

cout<<array[i]<<"\n";

system("pause");}

Slide 7- 23

Page 24: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Array of odd and array of even #include<iostream.h>

main()

{int count_a, count_b=0, count_c=0,a[5],b[5], c[5];

for( count_a=0; count_a<5; count_a++)

cin>>a[ count_a];

for( count_a=0; count_a<5; count_a++)

if ( a[ count_a] %2==0)

{b[ count_b ]=a[count_a];

count_b= count_b+1;}

else

{c[ count_c ]=a[count_a];

count_c= count_c+1;}

cout<<"items in array b is\n";

for( count_a=0; count_a< count_b; count_a++)

cout<< b[ count_a ]<<"\t";

cout<<"\nitems in array c is\n";

for( count_a=0; count_a< count_c; count_a++)

cout<< c[ count_a ]<<"\t";

system("pause");}

Slide 7- 24

Page 25: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Array summing

#include <iostream>

using namespace std;

int main()

{

int A[]={5,6,1,9,12,4,7};

int sum=0;

for(int i=0;i<7;i++)

{

cout<<A[i]<<" ";

sum+=A[i]; //sum =sum+A[i];

}

cout<<"\nsum= "<<sum<<endl;

return 0;

}

Slide 7- 25

Page 26: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

 Fibonacci series x−n = (−1)n+1 xn

#include<iostream> using namespace std; int f[1000]; int fib(int n) { f[0] = 0; f[1] = 1; for(int i=2; i<=n;i++) f[i] = f[i-1]+f[i-2]; return f[n]; } int main() { int n ; cout<< "Enter n: "; cin>> n; cout<< "\nfib(" << n << ") = " << fib(n) << endl; }

Slide 7- 26

Page 27: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

#include <iostream> using namespace std; int print(int a[][4]) { int i,j; for(i=0;i<4;i++) { for(j=0;j<4;j++) cout<<a[i][j]<<"\t"; cout<<"\n\n"; } } int main() { int X[4][4],i,j; int positives=0,negatives=0,zeros=0; int even=0,odd=0; for(i=0;i<4;i++) for(j=0;j<4;j++) { cout<<"X["<<i+1<<"]["<<j+1<<"]= "; cin>>X[i][j]; if(X[i][j]>0) positives++; if(X[i][j]<0) negatives++; if(X[i][j]==0) zeros++; if(X[i][j]%2==0) even++; if(X[i][j]%2!=0) odd++; }

Slide 7- 27

Page 28: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

cout<<"\n"; print(X);//printing X cout<<"\nnumber of positive elements="<<positives; cout<<"\nnumber of negative elements="<<negatives; cout<<"\nnumber of zeroth elements="<<zeros; cout<<"\nnumber of even elements="<<even; cout<<"\nnumber of odd elements="<<odd; cout<<"\nleading diagonal: "; for(i=0;i<4;i++) cout<<X[i][i]<<"\t"; cout<<"\ncross diagonal: "; for(i=0;i<4;i++) { for(j=0;j<4;j++) if(i+j==4-1) cout<<X[i][j]<<"\t"; } cout<<endl; system("pause"); return 0; }

Slide 7- 28

Page 29: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

// program to add matrix to another one #include <iostream> using namespace std; int main() { int a[10][10],b[10][10],c[10][10]; int i,j,m,n; cout<<"number of rows=";cin>>m; cout<<"number of columns=";cin>>n; for(i=0;i<m;i++) for(j=0;j<n;j++)

Slide 7- 29

Page 30: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

{ cout<<"a["<<i+1<<"]["<<j+1<<"]=";cin>>a[i][j]; cout<<"b["<<i+1<<"]["<<j+1<<"]=";cin>>b[i][j]; c[i][j]=a[i][j]+b[i][j]; } for(i=0;i<m;i++) { for(j=0;j<n;j++) cout<<a[i][j]<<" "; cout<<"\n"; } cout<<"\n +\n\n"; for(i=0;i<m;i++) { for(j=0;j<n;j++) cout<<b[i][j]<<" "; cout<<"\n"; } cout<<"\n =\n\n"; for(i=0;i<m;i++) { for(j=0;j<n;j++) cout<<c[i][j]<<" "; cout<<"\n"; } return 0; }

Slide 7- 30

Page 31: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

int array[5]={1,3,4,2,7}; int array[]={1,3,4,2,7}; array[0]=10 ; // arrays example #include <iostream>

using namespace std;

int m[] = {16, 2, 77, 40, 12071};

int i,sum=0;

int main ()

{

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

{

sum+= m[i];

}

cout <<sum;

system("pause");

return 0;

}

Slide 7- 31

Page 32: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Matrix in C++

int a[3][5]={{1,2,3,4,5},{2,4,6,8,10},{3,6,9,12,15}}; int a[3][5]={{1,3,4,5},{10},{12,15}};

Slide 7- 32

Page 33: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 33

Page 34: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 34

Page 35: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 35

Page 36: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 36

Page 37: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 37

Page 38: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 38

Page 39: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 39

Page 40: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

To declare an array in C++, the programmer specifies the type of the elements and the number of elements required by an array as follows:

type arrayName [ arraySize ]; double balance[10];

type arrayName [ arraySize ]; This is called a single-dimension array. The

arraySize must be an integer constant greater than zero and type can be any valid C++ data type. For example, to declare a 10-element array called balance of type double, use this statement:

Page 41: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Initializing Arrays Initializing Arrays: You can initialize C++ array elements either one by

one or using a single statement as follows: double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0}; The number of values between braces { } can not be

larger than the number of elements that we declare for the array between square brackets [ ].

Following is an example to assign a single element of the array:

If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write:

double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};

Page 42: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

balance[4] = 50.0; The above statement assigns element number 5th in the array a value of

50.0. Array with 4th index will be 5th i.e.. last element because all arrays have 0 as the index of their first element which is also called base index. Following is the pictorial representation of the same array we discussed above:

Page 43: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Two-Dimensional Arrays

type name[size1][size2]...[sizeN]; For example, the following declaration creates a

three dimensional 5 . 10 . 4 integer array: int threedim[5][10][4]; type arrayName [ x ][ y ]; // two dimensional

Page 44: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

initializing Two-Dimensional Arrays: Multi dimensioned arrays may be initialized by

specifying bracketed values for each row. Following is an array with 3 rows and each row have 4 columns.

int a[3][4] = {

{0, 1, 2, 3} , /* initializers for row indexed by 0 */

{4, 5, 6, 7} , /* initializers for row indexed by 1 */

{8, 9, 10, 11} /* initializers for row indexed by 2 */

};

Page 45: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

#include <iostream>using namespace std; int main (){ // an array with 5 rows and 2 columns. int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}}; // output each array element's value for ( int i = 0; i < 5; i++ ) for ( int j = 0; j < 2; j++ ) { cout << "a[" << i << "][" << j << "]: "; cout << a[i][j]<< endl; } return 0;}

Page 46: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Initialization of Two-Dimensional Array

Initialization of Two-Dimensional Array An two-dimensional array can be initialized along with declaration.

For two-dimensional array initialization, elements of each row are enclosed within curly braces and separated by commas.

All rows are enclosed within curly braces. int A[4][3] = {{22, 23, 10},               {15, 25, 13},               {20, 74, 67},               {11, 18, 14}};              {11, 18, 14}}; cout<<A[1][2];      //print an array element A[1][2]=13;         // assign value to an array element cin>>A[1][2];       //input element

Page 47: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Two-Dimensional Array

cout<<A[1][2];      //print an array element A[1][2]=13;         // assign value to an array element cin>>A[1][2];       //input element

Using Loop to input an Two-Dimensional Array from user

int mat[3][5], row, col ; for (row = 0; row < 3; row++) for (col = 0; col < 5; col++) cin >> mat[row][col];

Page 48: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.48

Program 7-7// This program uses an array of ten characters to store the// first ten letters of the alphabet. The ASCII codes of the// characters are displayed.#include <iostream.h>

void main(void){

char letters[10] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'};

cout << "Character" << "\t" << "ASCII Code\n";cout << "--------" << "\t" << "----------\n";for (int count = 0; count < 10; count++){

cout << letters[count] << "\t\t";cout << int(letters[count]) << endl;

}}

Page 49: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.49

Partial Array Initialization

When an array is being initialized, C++ does not require a value for every element.

int numbers[7] = {1, 2, 4, 8};

Page 50: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.50

Program 7-8

// This program has a partially initialized array.

#include <iostream.h>

void main(void){

int numbers[7] = {1, 2, 4, 8}; // Initialize the // first 4 elements.

cout << "Here are the contents of the array:\n";for (int index = 0; index < 7; index++)

cout << numbers[index] << endl;}

Page 51: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.51

Program Output

Here are the contents of the array:1248000

Page 52: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.52

Implicit (hidden) Array Sizing

It is possible to declare an array without specifying its size, as long as you provide an initialization list.

float ratings[] = {1.0, 1.5, 2.0, 2.5, 3.0};

Page 53: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.53

Initializing With Strings

When initializing a character array with a string, simply enclose the string in quotation marks:

char name[] = “Warren”;

Page 54: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.54

Figure 7-11

Page 55: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.55

Program 7-9

// This program displays the contents of two char arrays.#include <iostream.h>

void main(void){

char name1[] = "Holly";char name2[] = {'W', 'a', 'r', 'r', 'e', 'n', '\0'};

cout << name1 << endl;cout << name2 << endl;

}

Page 56: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.56

Program Output

HollyWarren

Page 57: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.57

7.5 Processing Array Contents

Individual array elements are processed like any other type of variable.

Page 58: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.58

Program 7-10// This program stores, in an array, the hours worked by 5// employees who all make the same hourly wage.

#include <iostream.h>

void main(void){

int hours[5];float payRate;

cout << "Enter the hours worked by 5 employees who all\n";cout << "earn the same hourly rate.\n";for (int index = 0; index < 5; index++){

cout << "Employee #" << (index + 1) << ": ";cin >> hours[index];

}

Page 59: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.59

Program continues

cout << "Enter the hourly pay rate for all the employees: ";cin >> payRate;cout << "Here is the gross pay for each employee:\n";cout.precision(2);cout.setf(ios::fixed | ios::showpoint);for (index = 0; index < 5; index++){

float grossPay = hours[index] * payRate;cout << "Employee #" << (index + 1);cout << ": $" << grossPay << endl;

}}

Page 60: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Multi array

#include <iostream.h>

main()

{ char months[12][10] = {"January", "February", "March",

"April", "May", "June",

"July", "August", "September",

"October", "November","December"};

int days[12] = { 31, 28, 31, 30,

31, 30, 31, 31,

30, 31, 30, 31};

for (int count = 0; count < 12; count++)

{ cout << months[count] << " has ";

cout << days[count] << " days.\n";

}

system("pause") ;

}

Page 61: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

String in array

#include <iostream>

using namespace std;

int main (){ char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

cout << "Greeting message: "; cout << greeting << endl;

return 0;}

Page 62: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

C++ supports a wide range of functions that manipulate null-terminated strings:

Page 63: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Page 64: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

#include <iostream>#include <cstring>

using namespace std;

int main (){ char str1[10] = "Hello"; char str2[10] = "World"; char str3[10]; int len ;

// copy str1 into str3 strcpy( str3, str1); cout << "strcpy( str3, str1) : " << str3 << endl;

// concatenates str1 and str2 strcat( str1, str2); cout << "strcat( str1, str2): " << str1 << endl;

// total lenghth of str1 after concatenation len = strlen(str1); cout << "strlen(str1) : " << len << endl;

return 0;}

Page 65: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Page 66: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Page 67: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Page 68: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Declaring Arrays: To declare an array in C++, the programmer specifies the type of the elements and the

number of elements required by an array as follows: type arrayName [ arraySize ]; This is called a single-dimension array. The arraySize must be an integer constant greater than zero and type can be any valid C+

+ data type. For example, to declare a 10-element array called balance of type double, use this statement:

double balance[10]; Initializing Arrays: You can initialize C++ array elements either one by one or using a single statement as

follows: double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0}; The number of values between braces { } can not be larger than the number of elements

that we declare for the array between square brackets [ ]. Following is an example to assign a single element of the array: If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write: double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};

Page 69: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

for-loops are commonly used to step througharrays Example: for (i = 0; i < 5; i++)

{ cout << score[i] << " off by " << (max – score[i]) << endl; }could display the difference between each score and the maximum score stored in an array

Slide 7- 69

First index is 0

Display 7.1

Loops And Arrays

Last index is (size – 1)

Page 70: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 70

Constants and Arrays

Use constants to declare the size of an array Using a constant allows your code to be easily

altered for use on a smaller or larger set of data Example: const int NUMBER_OF_STUDENTS = 50;

int score[NUMBER_OF_STUDENTS];

…for ( i = 0; i <

NUMBER_OF_STUDENTS; i++) cout << score[i] << " off by " << (max – score[i]) << endl;

Only the value of the constant must be changed to make this code work for any number of students

Page 71: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 71

Variables and Declarations

Most compilers do not allow the use of a variableto declare the size of an array

Example: cout << "Enter number of students: "; cin >> number; int score[number];

This code is illegal on many compilers

Page 72: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 72

Array Declaration Syntax

To declare an array, use the syntax: Type_Name Array_Name[Declared_Size]; Type_Name can be any type Declared_Size can be a constant to make your

program more versatile Once declared, the array consists of the indexed

variables: Array_Name[0] to Array_Name[Declared_Size -1]

Page 73: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 73

Computer Memory

Computer memory consists of numbered locations called bytes A byte's number is its address

A simple variable is stored in consecutive bytes The number of bytes depends on the variable's

type

A variable's address is the address of its first byte

Page 74: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Declaring the array int a[6] Reserves memory for six variables of type int The variables are stored one after another The address of a[0] is remembered

The addresses of the other indexed variables is not remembered

To determine the address of a[3] Start at a[0] Count past enough memory for three integers to

find a[3]

Slide 7- 74

Display 7.2

Arrays and Memory

Page 75: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 75

Array Index Out of Range

A common error is using a nonexistent index Index values for int a[6] are the values 0

through 5 An index value not allowed by the array

declaration is out of range Using an out of range index value doe not

produce an error message!

Page 76: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 76

Out of Range Problems

If an array is declared as: int a[6]; and an integer is declared as: int i = 7;

Executing the statement a[i] = 238; causes… The computer to calculate the address of the illegal

a[7] (This address could be where some other variable

is stored) The value 238 is stored at the address calculated

for a[7] No warning is given!

Page 77: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 77

Initializing Arrays

To initialize an array when it is declared The values for the indexed variables are

enclosed in braces and separated by commas Example: int children[3] = { 2, 12, 1 };

Is equivalent to: int children[3]; children[0] = 2; children[1] = 12;

children[2] = 1;

Page 78: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 78

Default Values

If too few values are listed in an initializationstatement The listed values are used to initialize the first

of the indexed variables The remaining indexed variables are initialized

to a zero of the base type Example: int a[10] = {5, 5};

initializes a[0] and a[1] to 5 and a[2] through a[9] to 0

Page 79: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 79

Un-initialized Arrays

If no values are listed in the array declaration, some compilers will initialize each variable to azero of the base type DO NOT DEPEND ON THIS!

Page 80: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 80

Section 7.1 Conclusion

Can you

Describe the difference between a[4] and int a[5]?

Show the output of

char symbol[3] = {'a', 'b', 'c'}; for (int index = 0; index < 3; index++) cout << symbol[index];

Page 81: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

7.2

Arrays in Functions

Page 82: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Indexed variables can be arguments to functions Example: If a program contains these declarations:

int i, n, a[10]; void my_function(int n);

Variables a[0] through a[9] are of type int, making these calls legal: my_function( a[ 0 ] ); my_function( a[ 3 ] ); my_function( a[ i ] );

Slide 7- 82

Display 7.3

Arrays in Functions

Page 83: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 83

Arrays as Function Arguments

A formal parameter can be for an entire array Such a parameter is called an array parameter

It is not a call-by-value parameter It is not a call-by-reference parameter Array parameters behave much like call-by-

reference parameters

Page 84: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 84

Array Parameter Declaration

An array parameter is indicated using emptybrackets in the parameter list such as

void fill_up(int a[ ], int size);

Page 85: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

If function fill_up is declared in this way: void fill_up(int a[ ], int size);

and array score is declared this way: int score[5], number_of_scores;

fill_up is called in this way: fill_up(score, number_of_scores);

Slide 7- 85

Display 7.4

Function Calls With Arrays

Page 86: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 86

Function Call Details

A formal parameter is identified as an array parameter by the [ ]'s with no index expression

void fill_up(int a[ ], int size);

An array argument does not use the [ ]'s

fill_up(score, number_of_scores);

Page 87: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 87

Array Formal Parameters

An array formal parameter is a placeholder forthe argument When an array is an argument in a function

call, an action performed on the array parameter is performed on the array argument

The values of the indexed variables can be changed by the function

Page 88: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 88

Array Argument Details

What does the computer know about an array? The base type The address of the first indexed variable The number of indexed variables

What does a function know about an array argument? The base type The address of the first indexed variable

Page 89: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 89

Array Parameter Considerations

Because a function does not know the size of an array argument… The programmer should include a formal

parameter that specifies the size of the array The function can process arrays of various

sizes Function fill_up from Display 7.4 can be used to fill

an array of any size:

fill_up(score, 5); fill_up(time, 10);

Page 90: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 90

const Modifier

Array parameters allow a function to change thevalues stored in the array argument

If a function should not change the values of thearray argument, use the modifier const

An array parameter modified with const is a constant array parameter Example:

void show_the_world(const int a[ ], int size);

Page 91: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 91

Using const With Arrays

If const is used to modify an array parameter:

const is used in both the function declaration and definition to modify the array parameter

The compiler will issue an error if you write code that changes the values stored in the array parameter

Page 92: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 92

Function Calls and const

If a function with a constant array parametercalls another function using the const arrayparameter as an argument…

The called function must use a constant array parameter as a placeholder for the array

The compiler will issue an error if a function is called that does not have a const array parameter to accept the array argument

Page 93: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 93

const Parameters Example

double compute_average(int a[ ], int size); void show_difference(const int a[ ], int size) { double average = compute_average(a, size); … }

compute_average has no constant array parameter This code generates an error message because

compute_average could change the array parameter

Page 94: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 94

Returning An Array

Recall that functions can return a value of type int, double, char, …, or a class type

Functions cannot return arrays

We learn later how to return a pointer to an array

Page 95: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 95

Case Study:Production Graph

Problem Definition: We are writing a program for the Apex Plastic

Spoon Company The program will display a bar graph showing the

production of each of four plants for a week Each plant has separate records for each

department Input is entered plant by plant Output shows one asterisk for each 1000 units, and

production is rounded to the nearest 1,000 units

Page 96: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 96

Analysis of The Problem

Use an array named production to hold total production of each plant Production for plant n is stored in production[n-1]

Program must scale production to nearest 1,000 units to display asterisks in the bar

Page 97: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 97

Production Graph Sub-Tasks

Analysis leads to the following sub-tasks input_data: Read input for each plant

Set production [plant_number -1]

to the total production for plant

number n scale: For each plant, change

production[plant_number] to the correct number of asterisks

graph: Output the bar graph

Page 98: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

The entire array will be an argument for the functions we write to perform the subtasks We will also include a formal parameter for the size The size of the array is equal to the number of plants We will use a constant for the number of plants

The function declarations and main function for the production graph program are found in

Slide 7- 98

Display 7.5

More Analysis Details

Page 99: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 99

Algorithm Design: input_data

We must read all departments' data for each plant and add them to produce a plant's total Algorithm for input_data:

for plant_number is 1, 2, …, last_plant_number

do the following Read all the data for plant number plant_number

Sum the numbers Set production[plant_number – 1] to the total

Page 100: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 100

Coding input_data The algorithm can be translated to C++ as:

void input_data(int a [ ], int last_plant_number){

using namespace std;

for (int plant_number = 1; plant_number <= last_plant_number; plant_number++) {

cout << endl; << "Enter production for plant" << plant_number << endl; get_total( a[plant_number -1] ); } }

Page 101: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Each function should be tested in a program in which it is the only untested function

Because input_data calls get_total, get_total is tested first

Once tested, get_total can be used to test input_data

Slide 7- 101

Display 7.6 (1)

Display 7.6 (2)

Display 7.6 (3)

Testing input_data

Page 102: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 102

Test Data for input_data

Remember that input_data should be tested With a plant that contains no production figures

With a plant having only one production figure

With a plant having more than one figure

With zero and non-zero production figures

Page 103: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 103

Algorithm for scale

scale changes the value of the indexed variableto show the whole number of asterisks to print Scale is called using

scale (production, NUMBER_OF_PLANTS);

and its algorithm is for (int index = 0; index < size; index++) Divide the value of a[index] by 1,000 and round the result to the nearest integer

Page 104: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 104

Why not 1000?

Coding scale

The code for scale, below, uses a function named

round that must be defined as well void scale(int a[ ], int size)

{ for (int index = 0; index < size; index++) a[index] = round (a[index] / 1000.0);}

Page 105: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 105

Function floor

Function round, called by scale, uses the floor function from the cmath library The floor function returns the first whole

number less than its argument: floor (3.4) returns 3 floor (3.9) returns 3

Adding 0.5 to the argument for floor is how round performs its task

floor (3.4 + 0.5) returns 3floor (3.9 + 0.5) returns 4

Page 106: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

To test scale First test round Scale should be tested with arguments that

Are 0 Round up Round down

Slide 7- 106

Display 7.7 (1)

Display 7.7 (2)

Testing scale

Page 107: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

The design of graph is quite straightforwardand not included here

The complete program to produce the bargraph is found in

Slide 7- 107

Display 7.8 (1)

Display 7.8 (2)

Display 7.8 (3)

Function graph

Page 108: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 108

Section 7.2 Conclusion

Can you

Write a function definition for a function called one_more, which has a formal parameter for an array of integers and increases the value of each array element by one. Are other formal parameters needed?

Page 109: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

7.3

Programming with Arrays

Page 110: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 110

Programming With Arrays

The size needed for an array is changeable Often varies from one run of a program to

another Is often not known when the program is written

A common solution to the size problem Declare the array size to be the largest that

could be needed Decide how to deal with partially filled arrays

Page 111: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

When using arrays that are partially filled Functions dealing with the array may not need

to know the declared size of the array, only how many elements are stored in the array

A parameter, number_used, may be sufficient to ensure that referenced index values are legal

A function such as fill_array in Display 7.9 needs to know the declared size of the array

Slide 7- 111

Display 7.9 (1) Display 7.9 (2) Display 7.9 (3)

Partially Filled Arrays

Page 112: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 112

Constants as Arguments

When function fill_array (Display 7.9) is called,MAX_NUMBER_SCORES is used as an argument Can't MAX_NUMBER_SCORES be used

directly without making it an argument? Using MAX_NUMBER_SCORES as an argument

makes it clear that fill_array requires the array's declared size

This makes fill_array easier to be used in other programs

Page 113: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 113

Searching Arrays

A sequential search is one way to searchan array for a given value Look at each element from first to last to see if

the target value is equal to any of the array elements

The index of the target value can be returned to indicate where the value was found in the array

A value of -1 can be returned if the value was not found

Page 114: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

The search function of Display 7.10… Uses a while loop to compare array elements

to the target value Sets a variable of type bool to true if the target

value is found, ending the loop Checks the boolean variable when the loop

ends to see if the target value was found Returns the index of the target value if found,

otherwise returns -1

Slide 7- 114

Display 7.10 (1) Display 7.10 (2)

The search Function

Page 115: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 115

Program Example:Sorting an Array

Sorting a list of values is very common task Create an alphabetical listing Create a list of values in ascending order Create a list of values in descending order

Many sorting algorithms exist Some are very efficient Some are easier to understand

Page 116: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 116

Program Example:The Selection Sort Algorithm

When the sort is complete, the elements of the array are ordered such that

a[0] < a[1] < … < a [ number_used -1] This leads to an outline of an algorithm:

for (int index = 0; index < number_used; index++) place the indexth smallest element in a[index]

Page 117: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

One array is sufficient to do our sorting Search for the smallest value in the array Place this value in a[0], and place the value

that was in a[0] in the location where the smallest was found

Starting at a[1], find the smallest remaining value swap it with the value currently in a[1]

Starting at a[2], continue the process until the array is sorted

Slide 7- 117

Display 7.11 Display 7.12 (1-2)

Program Example: Sort Algorithm Development

Page 118: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 118

Section 7.3 Conclusion

Can you

Write a program that will read up to 10 letters into an array and write the letters back to the screen in the reverse order?

abcd should be output as dcba

Use a period as a sentinel value to mark the end of input

Page 119: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

7.4

Multidimensional Arrays

Page 120: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 120

Multi-Dimensional Arrays

C++ allows arrays with multiple index values char page [30] [100];

declares an array of characters named page page has two index values:

The first ranges from 0 to 29The second ranges from 0 to 99

Each index in enclosed in its own brackets Page can be visualized as an array of

30 rows and 100 columns

Page 121: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 121

Index Values of page

The indexed variables for array page arepage[0][0], page[0][1], …, page[0][99]page[1][0], page[1][1], …, page[1][99]

…page[29][0], page[29][1], … , page[29][99]

page is actually an array of size 30 page's base type is an array of 100 characters

Page 122: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 122

Multidimensional Array Parameters

Recall that the size of an array is not neededwhen declaring a formal parameter: void display_line(const char a[ ], int size);

The base type of a multi-dimensional array mustbe completely specified in the parameter declaration void display_page(const char page[ ] [100],

int size_dimension_1);

Page 123: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 123

Program Example:Grading Program

Grade records for a class can be stored in a two-dimensional array For a class with 4 students and 3 quizzes the

array could be declared as

int grade[4][3]; The first array index refers to the number of a student The second array index refers to a quiz number

Since student and quiz numbers start with one, we subtract one to obtain the correct index

Page 124: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

The grading program uses one-dimensional arrays to store… Each student's average score Each quiz's average score

The functions that calculate these averagesuse global constants for the size of the arrays This was done because

the functions seem to be particular to this program

Slide 7- 124

Display 7.13 (1-3)

Display 7.14

Display 7.15

Grading Program:average scores

Page 125: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 125

Section 7.5 Conclusion

Can you

Write code that will fill the array a(declared below) with numbers typed at the keyboard? The numbers will be input fiver per line, on four lines.

int a[4][5];

Page 126: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Slide 7- 126

Chapter 7 - End

Page 127: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Display 7.1

Slide 7- 127

Back Next

Page 128: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Display 7.2

Slide 7- 128

Back Next

Page 129: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Display 7.3

Slide 7- 129

Back Next

Page 130: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Display 7.4

Slide 7- 130

Back Next

Page 131: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Display 7.5

Slide 7- 131

Back Next

Page 132: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Display 7.6 (1/3)

Slide 7- 132

Back Next

Page 133: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Display 7.6 (2/3)

Slide 7- 133

Back Next

Page 134: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Display 7.6 (3/3)

Slide 7- 134

Back Next

Page 135: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Display 7.7 (1/2)

Slide 7- 135

Back Next

Page 136: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Display 7.7(2/2)

Slide 7- 136

Back Next

Page 137: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Display 7.8 (1/4)

Slide 7- 137

NextBack

Page 138: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Display 7.8 (2/4)

Slide 7- 138

Back Next

Page 139: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Display 7.8 (3/4)

Slide 7- 139

NextBack

Page 140: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Display 7.8 (4/4)

Slide 7- 140

NextBack

Page 141: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Display 7.9 (1/3)

Slide 7- 141

Back Next

Page 142: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Display 7.9 (2/3)

Slide 7- 142

Back Next

Page 143: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Display 7.9(3/3)

Slide 7- 143

Back Next

Page 144: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Display 7.10 (1/2)

Slide 7- 144

NextBack

Page 145: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Display 7.10 (2/2)

Slide 7- 145

Back Next

Page 146: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Display 7.11

Slide 7- 146

Back Next

Page 147: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Display 7.12 (1/2)

Slide 7- 147

Back Next

Page 148: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Display 7.12 (2/2)

Slide 7- 148

Back Next

Page 149: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Display 7.13 (1/3)

Slide 7- 149

Back Next

Page 150: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Display 7.13 (2/3)

Slide 7- 150

Back Next

Page 151: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Display 7.13 (3/3)

Slide 7- 151

Back Next

Page 152: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Display 7.14

Slide 7- 152

Back Next

Page 153: Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Display 7.15

Slide 7- 153

Back Next