1 Arrays Outline Introduction Arrays Declaring Arrays Examples

  • Slides: 37
Download presentation
1 Arrays Outline Introduction Arrays Declaring Arrays Examples Using Arrays 2003 Prentice Hall, Inc.

1 Arrays Outline Introduction Arrays Declaring Arrays Examples Using Arrays 2003 Prentice Hall, Inc. All rights reserved.

2 Introduction • Arrays – Structures (collection) of related data items (same type data

2 Introduction • Arrays – Structures (collection) of related data items (same type data items) – Static entity (maintain the same size throughout program execution) 2003 Prentice Hall, Inc. All rights reserved.

3 Arrays • Array – Consecutive group of memory locations – Same name and

3 Arrays • Array – Consecutive group of memory locations – Same name and type (int, char, etc. ) • To refer to an element – – Specify array name and position number (index) Format: arrayname[ position_number ] An Array index must be an integer First element at position 0 • N-element array c c[ 0 ], c[ 1 ] … c[ n - 1 ] – Nth element as position N-1 2003 Prentice Hall, Inc. All rights reserved.

4 Arrays • Array elements like other variables – Assignment, printing for an integer

4 Arrays • Array elements like other variables – Assignment, printing for an integer array c c[ 0 ] = 3; cout << c[ 0 ]; • Can perform operations inside subscript c[ 5 – 2 ] same as c[3] int a = 6, b= 5; c[ a + b ] += 2; 2003 Prentice Hall, Inc. All rights reserved.

5 Arrays Name that this same of array (Note all elements of array have

5 Arrays Name that this same of array (Note all elements of array have the name, c) c[0] -45 c[1] 6 c[2] 0 c[3] 72 c[4] 1543 c[5] -89 c[6] 0 c[7] 62 c[8] -3 c[9] 1 c[10] 6453 c[11] 78 Position number of the element within array c 2003 Prentice Hall, Inc. All rights reserved. Value

6 Declaring Arrays • When declaring arrays, specify – Name – Type of array

6 Declaring Arrays • When declaring arrays, specify – Name – Type of array • Any data type – Number of elements – type array. Name[ array. Size ]; int c[ 10 ]; // array of 10 integers float d[ 3284 ]; // array of 3284 floats – array. Size: MUST be a positive integer • Declaring multiple arrays of same type – Use comma separated list, like regular variables int b[ 100 ], x[ 27 ]; 2003 Prentice Hall, Inc. All rights reserved.

7 Declaring Arrays • Array of type char can be used to store a

7 Declaring Arrays • Array of type char can be used to store a character string – string objects have so far been used to store character strings – Arrays can do the same thing (more later) 2003 Prentice Hall, Inc. All rights reserved.

8 Examples Using Arrays • Initializing arrays – For loop • Set each element

8 Examples Using Arrays • Initializing arrays – For loop • Set each element – Initializer list • Specify each element when array declared int n[ 5 ] = { 1, 2, 3, 4, 5 }; • If not enough initializers rightmost elements 0 • If too many syntax error – To set every element to same value int n[ 5 ] = { 0 }; – If array size omitted initializers determine size int n[] = { 1, 2, 3, 4, 5 }; • 5 initializers, therefore 5 element array 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 // Fig. 7. 3: fig 07_03. cpp // Initializing an array.

1 2 3 // Fig. 7. 3: fig 07_03. cpp // Initializing an array. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <iomanip> 9 10 using std: : setw; 11 12 13 14 int main() { int n[ 10 ]; Outline Declare a 10 -element array of integers. array // n is an array of Initialize 10 integers to 0 using a for loop. Note that the array has n[0] to n[9]. n elements to 0 15 16 17 18 // initialize elements of array for ( int i = 0; i < 10; i++ ) n[ i ] = 0; // set element at location i to 0 19 20 cout << "Element" << setw( 13 ) << "Value" << endl; 21 22 23 24 // output contents of array n in tabular format for ( int j = 0; j < 10; j++ ) cout << setw( 7 ) << j << setw( 13 ) << n[ j ] << endl; 25 2003 Prentice Hall, Inc. All rights reserved. 9

26 27 28 return 0; // indicates successful termination Outline } // end main

26 27 28 return 0; // indicates successful termination Outline } // end main Element 0 1 2 3 4 5 6 7 8 9 Value 0 0 0 0 0 2003 Prentice Hall, Inc. All rights reserved. 10

1 2 3 // Fig. 7. 4: fig 07_04. cpp // Initializing an array

1 2 3 // Fig. 7. 4: fig 07_04. cpp // Initializing an array with a declaration. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <iomanip> 9 10 using std: : setw; 11 12 13 14 15 16 17 Note the use of the initializer int main() list. { // use initializer list to initialize array n int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 }; cout << "Element" << setw( 13 ) << "Value" << endl; 18 19 20 21 // output contents of array n in tabular format for ( int i = 0; i < 10; i++ ) cout << setw( 7 ) << i << setw( 13 ) << n[ i ] << endl; 22 23 return 0; 24 25 Outline // indicates successful termination } // end main 2003 Prentice Hall, Inc. All rights reserved. 11

Element 0 1 2 3 4 5 6 7 8 9 Value 32 27

Element 0 1 2 3 4 5 6 7 8 9 Value 32 27 64 18 95 14 90 70 60 37 Outline 2003 Prentice Hall, Inc. All rights reserved. 12

13 Examples Using Arrays • Array size – Can be specified with constant variable

13 Examples Using Arrays • Array size – Can be specified with constant variable (const) • const int size = 20; – Constants cannot be changed – Constants must be initialized when declared – Also called named constants or read-only variables 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 // Fig. 7. 5: fig 07_05. cpp // Initialize array s

1 2 3 // Fig. 7. 5: fig 07_05. cpp // Initialize array s to the even integers from 2 to 20. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <iomanip> 9 10 using std: : setw; 11 12 13 14 15 16 17 Note use of const keyword. can int main() Only const variables { specify array sizes. // constant variable can be used to specify array size const int array. Size = 10; int s[ array. Size ]; // array s 18 19 20 for ( int i = 0; i < array. Size; s[ i ] = 2 + 2 * i; 21 22 cout << "Element" << setw( 13 ) 23 Outline The program becomes more scalable when we set the array has 10 elements size using a const variable. i++ ) // We setcan thechange valuesarray. Size, and all the loops will still work (otherwise, we’d have to << "Value"update << endl; every loop in the program). 2003 Prentice Hall, Inc. All rights reserved. 14

24 25 26 // output contents of array s in tabular format for (

24 25 26 // output contents of array s in tabular format for ( int j = 0; j < array. Size; j++ ) cout << setw( 7 ) << j << setw( 13 ) << s[ j ] << endl; 27 28 return 0; 29 30 Outline // indicates successful termination } // end main Element 0 1 2 3 4 5 6 7 8 9 Value 2 4 6 8 10 12 14 16 18 20 2003 Prentice Hall, Inc. All rights reserved. 15

1 2 3 // Fig. 7. 6: fig 07_06. cpp // Using a properly

1 2 3 // Fig. 7. 6: fig 07_06. cpp // Using a properly initialized constant variable. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 9 10 int main() { const int x = 7; Proper initialization of const variable. (cannot be modified later) // initialized constant variable 11 12 13 cout << "The value of constant variable x is: " << x << endl; 14 15 return 0; 16 17 Outline // indicates successful termination } // end main The value of constant variable x is: 7 2003 Prentice Hall, Inc. All rights reserved. 16

1 2 // Fig. 7. 7: fig 07_07. cpp // A const object must

1 2 // Fig. 7. 7: fig 07_07. cpp // A const object must be initialized. 3 4 5 6 int main() { const int x; // Error: x Uninitialized const results in a syntax error. Attempting to modify the const is must be initialized another error. 7 8 x = 7; // Error: cannot modify a const variable 9 10 return 0; // indicates successful termination 11 12 Outline } // end main d: cpphtp 7_examplesch 04Fig 07_07. cpp(8) : error C 2166: l-value specifies const object 2003 Prentice Hall, Inc. All rights reserved. 17

Summing the elements of an array 1 2 3 // Fig. 7. 8: fig

Summing the elements of an array 1 2 3 // Fig. 7. 8: fig 07_08. cpp // Compute the sum of the elements of the array. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 9 10 int main() { const int array. Size = 10; 11 12 int a[ array. Size ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 13 14 int total = 0; 15 16 17 18 19 20 21 22 23 24 Outline // sum contents of array a for ( int i = 0; i < array. Size; i++ ) total += a[ i ]; cout << "Total of array element values is " << total << endl; return 0; // indicates successful termination } // end main Total of array element values is 55 2003 Prentice Hall, Inc. All rights reserved. 18

19 Showing array data graphically – Example: show distribution of grades of a specific

19 Showing array data graphically – Example: show distribution of grades of a specific class – Grade distribution is stored in an array of 11 elements, each corresponds to a category of grade • Example: – category 1: [0. . 9] – category 2: [10. . 19] – etc… 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 // Fig. 7. 9: fig 07_09. cpp // Histogram printing program.

1 2 3 // Fig. 7. 9: fig 07_09. cpp // Histogram printing program. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <iomanip> 9 10 using std: : setw; 11 12 13 14 15 int main() { const int array. Size = 11; int n[ array. Size ] = { 0, 0, 0, 1, 2, 4, 2, 1 }; 16 17 cout << “Grade Distribution: " << endl; 18 19 20 21 22 23 24 25 26 27 // for each for ( int i // output if (i == cout else if cout else cout Outline element of array n, output a bar in histogram = 0; i < array. Size; i++ ) { bar labels (“ 0 -9: ”, …“ 90 -99: ”, “ 100: ”) 0) << “ 0 -9: ”; (i == 10) << “ 100: ”; << i * 10 << “-” << (i * 10) + 9<< “: ”; 2003 Prentice Hall, Inc. All rights reserved. 20

28 29 30 // print bar of asterisks for ( int stars = 0;

28 29 30 // print bar of asterisks for ( int stars = 0; stars < n[ i ]; stars++ ) cout << '*'; 31 32 cout << endl; 33 34 35 36 37 // start next line of output Outline Number of students with grades in the range: 10*i--10*i+9. } // end outer for structure return 0; // indicates successful termination } // end main Grade distribution 0 -9: 10 -19: 20 -29: 30 -39: 40 -49: 50 -59: 60 -69: * 70 -79: * * 80 -89: * * 90 -99: * * 2003 Prentice Hall, Inc. All rights reserved. 21

Outline Using Elements of array as counters 1 2 3 // Fig. 7. 10:

Outline Using Elements of array as counters 1 2 3 // Fig. 7. 10: fig 07_10. cpp // Roll a six-sided die 6000000 times. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <iomanip> 9 10 using std: : setw; 11 12 13 #include <cstdlib> #include <ctime> 14 15 16 17 18 int main() { const int array. Size = 7; // ignore element zero This int frequency[ array. Size ] = { 0 }; Remake of old program to roll dice. An array is used instead of 6 regular variables, and the proper element can be updated easily (without needing a switch). creates a number between 1 and 6, which determines the index of generator frequency[] that should be incremented. 19 20 srand( time( 0 ) ); 21 22 23 24 // roll die 6000000 times for ( int roll = 1; roll <= 6000000; roll++ ) frequency[ 1 + rand() % 6 ]++; 25 // seed random-number 2003 Prentice Hall, Inc. All rights reserved. 22

26 27 cout << "Face" << setw( 13 ) << "Frequency" << endl; 28

26 27 cout << "Face" << setw( 13 ) << "Frequency" << endl; 28 29 30 31 32 // output frequency elements 1 -6 in tabular format for ( int face = 1; face < array. Size; face++ ) cout << setw( 4 ) << face << setw( 13 ) << frequency[ face ] << endl; 33 34 return 0; 35 36 Outline // indicates successful termination } // end main Face 1 2 3 4 5 6 Frequency 1000167 1000149 1000152 998748 999626 1001158 2003 Prentice Hall, Inc. All rights reserved. 23

24 Using arrays to summarize survey results Forty students were asked to rate the

24 Using arrays to summarize survey results Forty students were asked to rate the quality of the food in the student cafeteria on a scale of 1 to 10 (1 meaning awful and 10 meaning excellent). Place the 40 responses in an integer array and summarize the results of the poll 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 // Fig. 7. 11: fig 07_11. cpp // Student poll program.

1 2 3 // Fig. 7. 11: fig 07_11. cpp // Student poll program. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <iomanip> 9 10 using std: : setw; 11 12 13 14 15 16 int main() { // define array sizes const int response. Size = 40; const int frequency. Size = 11; Outline Array declared as const int this means its value cannot and should not change // size of array responses // size of array frequency 17 18 19 20 21 // place survey responses in array responses const int responses[ response. Size ] = { 1, 2, 6, 4, 8, 5, 9, 7, 8, 10, 1, 6, 3, 8, 6, 10, 3, 8, 2, 7, 6, 5, 7, 6, 8, 6, 7, 5, 6, 6, 5, 6, 7, 5, 6, 4, 8, 6, 8, 10 }; 22 23 24 // initialize frequency counters to 0 int frequency[ frequency. Size ] = { 0 }; 25 2003 Prentice Hall, Inc. All rights reserved. 25

26 27 28 29 30 // for each answer, select value of an element

26 27 28 29 30 // for each answer, select value of an element of array // responses and use that value as subscript in array // frequency to determine element to increment for ( int answer = 0; answer < response. Size; answer++ ) frequency[ responses[answer] ]++; 31 32 33 // display results the rating (from 1 to 10). cout << "Rating" << setw( 17 ) << "Frequency" << endl; 34 35 36 37 38 // output frequencies in tabular for ( int rating = 1; rating < frequency. Size; rating++ ) cout << setw( 6 ) << rating << setw( 17 ) << frequency[ rating ] << endl; 39 40 return 0; 41 42 Outline responses[answer] is This determines the index in frequency[] to increment. format // indicates successful termination } // end main 2003 Prentice Hall, Inc. All rights reserved. 26

Rating 1 2 3 4 5 6 7 8 9 10 Frequency 2 2

Rating 1 2 3 4 5 6 7 8 9 10 Frequency 2 2 5 11 5 7 1 3 Outline NOTE: what happens when the data in responses contain an invalid value (e. g. , 13)… C++ does not do a boundary check logic error happens (NOT SYNTAX ERROR) 2003 Prentice Hall, Inc. All rights reserved. 27

Using character arrays to store and manipulate strings • string has been used to

Using character arrays to store and manipulate strings • string has been used to store character strings – A string such as “Hello” is an array of characters • A character array can be declared and initialized as: – char string 1[] = “first”; – The size of array string 1 is not explicitly defined, but it is determined by the compiler based on the length of the string. – NOTE: • all strings represented by a character array ends with a special character (the null character ‘’) • A character array representing a string should be defined large enough to hold the number of characters in the string + the termination character 2003 Prentice Hall, Inc. All rights reserved. 28

Using character arrays to store and manipulate strings • One could also use this

Using character arrays to store and manipulate strings • One could also use this method to declare strings: char string 1[] = {‘f’, ‘i’, ‘r’, ‘s’, ‘t’, ‘’}; If you don’t use ‘’, the array would simply represent an array of characters, not a string! if you specify the size of string 1 and the size of “list of initializers” is larger syntax error • char arrays can be manipulated as other arrays, example: – string[0] = ‘f’; 2003 Prentice Hall, Inc. All rights reserved. 29

Using character arrays to store and manipulate strings • Input from keyboard char string

Using character arrays to store and manipulate strings • Input from keyboard char string 2[ 20 ]; cin >> string 2; – Puts user input in string • Stops at first whitespace character • Adds null character – If too much text entered, data written beyond array • We want to avoid this • Printing strings – cout << string 2 << endl; • Does not work for other array types – Characters printed until null found 2003 Prentice Hall, Inc. All rights reserved. 30

1 2 3 4 5 6 // Fig. 7. 12: fig 07_12. cpp //

1 2 3 4 5 6 // Fig. 7. 12: fig 07_12. cpp // treating character arrays as strings. #include <iostream> using std: : cout; using std: : cin; using std: : endl; Outline 7 8 int main() 9 { 10 char string 1 [20]; // reserve 20 characters 11 char string 2 [] = “string literal”; // reserve 15 characters 12 13 14 15 // read string from user into array string 1 cout << “Enter the string “hello there”: ” ; cin >> string 1; // read “hello” [space terminates input] 16 17 18 19 // output strings cout << “string 1 is: ” << string 1 << “nstring 2 is: ” << string 2; cout << “nstring 1 with spaces between characters is: n” ; 20 21 22 23 // output characters until null character is reached for ( int i = 0; string 1[ i ]!= ‘’; i++ ) cout << string 1[ i ] << ‘ ’; 24 25 26 cin >> string 1; // reads “there” cout << “nstring 1 is: ” << string 1 <<endl; 27 28 29 return 0; // indicates successful termination } // end main 2003 Prentice Hall, Inc. All rights reserved. 31

Enter the string “hello there”: hello there string 1 is: hello string 2 is:

Enter the string “hello there”: hello there string 1 is: hello string 2 is: string literal string 1 with spaces between characters is: h e l l o string 1 is: there Outline 2003 Prentice Hall, Inc. All rights reserved. 32

33 Static and automatic local variables • Recall static storage – If static, local

33 Static and automatic local variables • Recall static storage – If static, local variables save values between function calls – Visible only in function body – Can declare local arrays to be static • Initialized to zero static int array[3]; • If not static – Created (and destroyed) in every function call 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 // Fig. 7. 13: fig 07_13. cpp // Static arrays are

1 2 3 // Fig. 7. 13: fig 07_13. cpp // Static arrays are initialized to zero. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 9 void static. Array. Init( void ); void automatic. Array. Init( void ); 10 11 12 13 14 15 int main() { cout << "First call to each function: n" ; static. Array. Init(); automatic. Array. Init(); // function prototype 16 17 18 19 20 cout << "nn. Second call to each function: n" ; static. Array. Init(); automatic. Array. Init(); cout << endl; 21 22 return 0; 23 24 Outline // indicates successful termination } // end main 25 2003 Prentice Hall, Inc. All rights reserved. 34

26 27 28 29 30 // function to demonstrate a static local array Static

26 27 28 29 30 // function to demonstrate a static local array Static array, initialized to zero void static. Array. Init( void ) on first function call. { // initializes elements to 0 first time function is called static int array 1[ 3 ]; 31 32 cout << "n. Values on entering static. Array. Init: n"; 33 34 35 36 // output contents of array 1 for ( int i = 0; i < 3; i++ ) cout << "array 1[" << i << "] = " << array 1[ i ] << " 37 38 cout << "n. Values on exiting static. Array. Init: n"; 39 40 41 42 43 // modify and output for ( int j = 0; j < cout << "array 1[" << ( array 1[ 44 45 Outline "; Array data is changed; the modified values stay. contents of array 1 3; j++ ) << j << "] = " j ] += 5 ) << " "; } // end function static. Array. Init 46 2003 Prentice Hall, Inc. All rights reserved. 35

47 48 49 50 51 // function to demonstrate an automatic local array void

47 48 49 50 51 // function to demonstrate an automatic local array void automatic. Array. Init( void ) Automatic array, recreated { with every function call. // initializes elements each time function is called int array 2[ 3 ] = { 1, 2, 3 }; 52 53 cout << "nn. Values on entering automatic. Array. Init: n"; 54 55 56 57 // output contents of array 2 for ( int i = 0; i < 3; i++ ) cout << "array 2[" << i << "] = " << array 2[ i ] << " 58 59 cout << "n. Values on exiting automatic. Array. Init: n"; 60 61 62 63 64 // modify and output for ( int j = 0; j < cout << "array 2[" << ( array 2[ 65 66 contents of array 2 3; j++ ) << j << "] = " j ] += 5 ) << " "; Outline "; Although the array is changed, it will be destroyed when the function exits and the changes will be lost. } // end function automatic. Array. Init 2003 Prentice Hall, Inc. All rights reserved. 36

First call to each function: Values on array 1[0] entering static. Array. Init: =

First call to each function: Values on array 1[0] entering static. Array. Init: = 0 array 1[1] = 0 array 1[2] = 0 exiting static. Array. Init: = 5 array 1[1] = 5 array 1[2] = 5 Values on array 2[0] entering automatic. Array. Init: = 1 array 2[1] = 2 array 2[2] = 3 exiting automatic. Array. Init: = 6 array 2[1] = 7 array 2[2] = 8 Outline Second call to each function: Values on array 1[0] entering static. Array. Init: = 5 array 1[1] = 5 array 1[2] = 5 exiting static. Array. Init: = 10 array 1[1] = 10 array 1[2] = 10 Values on array 2[0] entering automatic. Array. Init: = 1 array 2[1] = 2 array 2[2] = 3 exiting automatic. Array. Init: = 6 array 2[1] = 7 array 2[2] = 8 2003 Prentice Hall, Inc. All rights reserved. 37