Lecture 7 Arrays 1 4 1 Introduction n

  • Slides: 40
Download presentation
Lecture 7 Arrays 1

Lecture 7 Arrays 1

4. 1 Introduction n Arrays q q Structures of related data items Static entity

4. 1 Introduction n Arrays q q Structures of related data items Static entity (same size throughout program) 2

4. 2 Arrays n Array q q n To refer to an element q

4. 2 Arrays n Array q q n To refer to an element q q q n Consecutive group of memory locations Same name and type (int, char, etc. ) Specify array name and position number (index) Format: arrayname[ position number ] First element at position 0 N-element array c c[ 0 ], c[ 1 ] … c[ n - 1 ] q Nth element as position N-1 3

4. 2 Arrays n Array elements like other variables q Assignment, printing for an

4. 2 Arrays n Array elements like other variables q Assignment, printing for an integer array c c[ 0 ] = 3; cout << c[ 0 ]; n Can perform operations inside subscript c[ 5 – 2 ] same as c[3] 4

4. 2 Arrays Name of array (Note that all elements of this array have

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

4. 3 Declaring Arrays n When declaring arrays, specify q q Name Type of

4. 3 Declaring Arrays n When declaring arrays, specify q q Name Type of array n q q 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 n Declaring multiple arrays of same type q Use comma separated list, like regular variables int b[ 100 ], x[ 27 ]; 6

4. 4 Examples Using Arrays n Initializing arrays q For loop n q Set

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

1 2 3 4 5 6 7 8 9 10 11 12 13 14

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

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

26 27 28 return 0; // indicates successful termination } // end main Element 0 1 2 3 4 5 6 7 8 9 Value 0 0 0 0 0 fig 04_03. cpp (2 of 2) fig 04_03. cpp output (1 of 1) 9

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // Fig. 4. 4: fig 04_04. cpp // Initializing an array with a declaration. #include <iostream> fig 04_04. cpp (1 of 1) using std: : cout; using std: : endl; #include <iomanip> using std: : setw; Note the use of the initializer list. int main() { // 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; // output contents of array n in tabular format for ( int i = 0; i < 10; i++ ) cout << setw( 7 ) << i << setw( 13 ) << n[ i ] << endl; return 0; // indicates successful termination } // end main 10

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 fig 04_04. cpp output (1 of 1) 11

4. 4 Examples Using Arrays n Array size q Can be specified with constant

4. 4 Examples Using Arrays n Array size q Can be specified with constant variable (const) n q q q const int SIZE = 20; Constants cannot be changed Constants must be initialized when declared Also called named constants or read-only variables 12

1 2 3 4 5 6 7 8 9 10 11 12 13 14

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

24 25 26 27 28 29 30 // output contents of array s in

24 25 26 27 28 29 30 // output contents of array s in tabular format for ( int j = 0; j < ARRAYSIZE; j++ ) cout << setw( 7 ) << j << setw( 13 ) << s[ j ] << endl; return 0; // 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 fig 04_05. cpp (2 of 2) fig 04_05. cpp output (1 of 1) 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 // Fig. 4. 6: fig 04_06. cpp // Using a properly initialized constant variable. #include <iostream> fig 04_06. cpp (1 of 1) using std: : cout; using std: : endl; fig 04_06. cpp output (1 of 1) Proper initialization of const variable. int main() { const int X = 7; // initialized constant variable cout << "The value of constant variable x is: " << X << endl; return 0; // indicates successful termination } // end main The value of constant variable x is: 7 15

1 2 3 4 5 6 7 8 9 10 11 12 // Fig.

1 2 3 4 5 6 7 8 9 10 11 12 // Fig. 4. 7: fig 04_07. cpp // A const object must be initialized. Uninitialized const results int main() in a syntax error. Attempting { to modify the const is const int X; // Error: x mustanother be initialized error. X = 7; // Error: cannot modify a const variable return 0; // indicates successful termination fig 04_07. cpp (1 of 1) fig 04_07. cpp output (1 of 1) } // end main d: cpphtp 4_examplesch 04Fig 04_07. cpp(6) : error C 2734: 'x' : const object must be initialized if not extern d: cpphtp 4_examplesch 04Fig 04_07. cpp(8) : error C 2166: l-value specifies const object 16

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 // Fig. 4. 8: fig 04_08. cpp // Compute the sum of the elements of the array. #include <iostream> using std: : cout; using std: : endl; int main() { const int ARRAYSIZE = 10; fig 04_08. cpp (1 of 1) fig 04_08. cpp output (1 of 1) int a[ ARRAYSIZE ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int total = 0; // sum contents of array a for ( int i = 0; i < ARRAYSIZE; 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 17

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // Fig. 4. 9: fig 04_09. cpp // Histogram printing program. #include <iostream> using std: : cout; using std: : endl; fig 04_09. cpp (1 of 2) #include <iomanip> using std: : setw; int main() { const int ARRAYSIZE = 10; int n[ ARRAYSIZE ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 }; cout << "Element" << setw( 13 ) << "Value" << setw( 17 ) << "Histogram" << endl; // for each element of array n, output a bar in histogram for ( int i = 0; i < ARRAYSIZE; i++ ) { Prints asterisks corresponding cout << setw( 7 ) << i << setw( 13 ) to size of array element, << n[ i ] << setw( 9 ); n[i]. for ( int j = 0; j < n[ i ]; j++ ) // print one bar cout << '*'; 18

27 28 29 30 31 32 33 34 cout << endl; // start next

27 28 29 30 31 32 33 34 cout << endl; // start next line of output fig 04_09. cpp (2 of 2) } // end outer for structure return 0; // indicates successful termination fig 04_09. cpp output (1 of 1) } // end main Element 0 1 2 3 4 5 6 7 8 9 Value 19 3 15 7 11 9 13 5 17 1 Histogram ********** *********** *********** * 19

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // Fig. 4. 10: fig 04_10. cpp // Roll a six-sided die 6000 times. #include <iostream> fig 04_10. cpp (1 of 2) using std: : cout; using std: : endl; #include <iomanip> using std: : setw; #include <cstdlib> #include <ctime> int main() { const int ARRAYSIZE= 7; int frequency[ ARRAYSIZE ] = { 0 }; srand( time( 0 ) ); // seed random-number generator // roll die 6000 times for ( int roll = 1; roll <= 6000; roll++ ) ++frequency[ 1 + rand() % 6 ]; // replaces 20 -line switch // of Fig. 3. 8 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). This creates a number between 1 and 6, which determines the index of frequency[] that should be incremented. 20

26 27 28 29 30 31 32 33 34 35 36 cout << "Face"

26 27 28 29 30 31 32 33 34 35 36 cout << "Face" << setw( 13 ) << "Frequency" << endl; // output frequency elements 1 -6 in tabular format for ( int face = 1; face < ARRAYSIZE; face++ ) cout << setw( 4 ) << face << setw( 13 ) << frequency[ face ] << endl; fig 04_10. cpp (2 of 2) fig 04_10. cpp output (1 of 1) return 0; // indicates successful termination } // end main Face 1 2 3 4 5 6 Frequency 1003 1004 999 980 1013 1001 21

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // Fig. 4. 11: fig 04_11. cpp // Student poll program. #include <iostream> using std: : cout; using std: : endl; fig 04_11. cp p (1 of 2) #include <iomanip> using std: : setw; int main() { // define array sizes const int RESPONSESIZE = 40; // size of array responses const int FREQUENCYSIZE = 11; // size of array frequency // place survey responses in array responses int responses[ RESPONSESIZE ] = { 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 }; // initialize frequency counters to 0 int frequency[ FREQUENCYSIZE ] = { 0 }; 22

26 27 28 29 30 31 32 33 34 35 36 37 38 39

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 // 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 < RESPONSESIZE; answer++ ) ++frequency[ responses[answer] ]; fig 04_11. cpp (2 of 2) responses[answer] is the rating (from 1 to 10). This // display results determines the index in cout << "Rating" << setw( 17 ) << "Frequency" << endl; frequency[] to increment. // output frequencies in tabular format for ( int rating = 1; rating < FREQUENCYSIZE; rating++ ) cout << setw( 6 ) << rating << setw( 17 ) << frequency[ rating ] << endl; return 0; // indicates successful termination } // end main 23

fig 04_11. cpp output (1 of 1) Rating 1 2 3 4 5 6

fig 04_11. cpp output (1 of 1) Rating 1 2 3 4 5 6 7 8 9 10 Frequency 2 2 5 11 5 7 1 3 24

4. 4 Examples Using Arrays n Strings (more in ch. 5) q Arrays of

4. 4 Examples Using Arrays n Strings (more in ch. 5) q Arrays of characters All strings end with null ('') q Examples q n char string 1[] = "hello"; q q n q Null character implicitly added string 1 has 6 elements char string 1[] = { 'h', 'e', 'l', 'o', '’ }; Subscripting is the same String 1[ 0 ] is 'h' string 1[ 2 ] is 'l' 25

4. 4 Examples Using Arrays n Input from keyboard char string 2[ 10 ];

4. 4 Examples Using Arrays n Input from keyboard char string 2[ 10 ]; cin >> string 2; q Puts user input in string n n q If too much text entered, data written beyond array n n Stops at first whitespace character Adds null character We want to avoid this (section 5. 12 explains how) Printing strings q cout << string 2 << endl; n q Does not work for other array types Characters printed until null found 26

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 fig 04_12. cpp (1 of 2) // Fig. 4_12: fig 04_12. cpp // Treating character arrays as strings. #include <iostream> using std: : cout; using std: : cin; using std: : endl; Two different ways to declare strings. string 2 is initialized, and its size determined automatically. int main() { char string 1[ 20 ], // reserves 20 characters char string 2[] = "string literal"; // reserves 15 characters // read string from user into array string 2 cout << "Enter the string "hello there": "; cin >> string 1; // reads "hello" [space terminates input] Examples of reading strings from the keyboard and printing them out. // output strings cout << "string 1 is: " << string 1 << "nstring 2 is: " << string 2; cout << "nstring 1 with spaces between characters is: n"; 27

24 25 26 27 28 29 30 31 32 33 // output characters until

24 25 26 27 28 29 30 31 32 33 // output characters until null character is reached for ( int i = 0; string 1[ i ] != ''; i++ ) cout << string 1[ i ] << ' '; Can access the characters in a fig 04_12. cpp (2 of 2) string using array notation. The loop ends when the null character is found. cin >> string 1; // reads "there" cout << "nstring 1 is: " << string 1 << endl; return 0; // indicates successful termination fig 04_12. cpp output (1 of 1) } // end main 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 28

4. 4 Examples Using Arrays n Recall static storage (chapter 3) q q q

4. 4 Examples Using Arrays n Recall static storage (chapter 3) q q q 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]; n n If not static q Created (and destroyed) in every function call 29

1 2 3 4 5 6 7 8 9 10 11 12 13 14

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

26 27 28 29 30 31 32 33 34 35 36 37 38 39

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

47 48 49 50 51 52 53 54 55 56 57 58 59 60

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 // 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 }; fig 04_13. cpp (3 of 3) cout << "nn. Values on entering automatic. Array. Init: n"; // output contents of array 2 for ( int i = 0; i < 3; i++ ) cout << "array 2[" << i << "] = " << array 2[ i ] << " "; cout << "n. Values on exiting automatic. Array. Init: n"; // modify and output contents of array 2 for ( int j = 0; j < 3; j++ ) cout << "array 2[" << j << "] = " << ( array 2[ j ] += 5 ) << " "; Although the array is changed, it will be destroyed when the function exits and the changes will be lost. } // end function automatic. Array. Init 32

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

First call to each function: Values on entering static. Array. Init: array 1[0] = 0 array 1[1] = 0 array 1[2] = 0 Values on exiting static. Array. Init: array 1[0] = 5 array 1[1] = 5 array 1[2] = 5 fig 04_13. cpp output (1 of 1) Values on entering automatic. Array. Init: array 2[0] = 1 array 2[1] = 2 array 2[2] = 3 Values on exiting automatic. Array. Init: array 2[0] = 6 array 2[1] = 7 array 2[2] = 8 Second call to each function: Values on entering static. Array. Init: array 1[0] = 5 array 1[1] = 5 array 1[2] = 5 Values on exiting static. Array. Init: array 1[0] = 10 array 1[1] = 10 array 1[2] = 10 Values on entering automatic. Array. Init: array 2[0] = 1 array 2[1] = 2 array 2[2] = 3 Values on exiting automatic. Array. Init: array 2[0] = 6 array 2[1] = 7 array 2[2] = 8 33

4. 5 Passing Arrays to Functions n Specify name without brackets q To pass

4. 5 Passing Arrays to Functions n Specify name without brackets q To pass array my. Array to my. Function int my. Array[ 24 ]; my. Function( my. Array, 24 ); q Array size usually passed, but not required n Useful to iterate over all elements 34

4. 5 Passing Arrays to Functions n Arrays passed-by-reference q q Functions can modify

4. 5 Passing Arrays to Functions n Arrays passed-by-reference q q Functions can modify original array data Value of name of array is address of first element n n n Function knows where the array is stored Can change original memory locations Individual array elements passed-by-value q q Like regular variables square( my. Array[3] ); 35

4. 5 Passing Arrays to Functions n Functions taking arrays q Function prototype n

4. 5 Passing Arrays to Functions n Functions taking arrays q Function prototype n n void modify. Array( int b[], int array. Size ); void modify. Array( int [], int ); q n q Names optional in prototype Both take an integer array and a single integer No need for array size between brackets n Ignored by compiler 36

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // Fig. 4. 14: fig 04_14. cpp // Passing arrays and individual array elements to functions. #include <iostream> fig 04_14. cpp (1 of 3) using std: : cout; using std: : endl; #include <iomanip> using std: : setw; Syntax for accepting an array in parameter list. void modify. Array( int [], int ); // appears strange void modify. Element( int ); int main() { const int ARRAYSIZE = 5; // size of array a int a[ ARRAYSIZE ] = { 0, 1, 2, 3, 4 }; // initialize a cout << "Effects of passing entire array by reference: " << "nn. The values of the original array are: n"; // output original array for ( int i = 0; i < ARRAYSIZE; i++ ) cout << setw( 3 ) << a[ i ]; 37

26 27 28 29 30 31 32 33 34 35 36 37 38 39

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 cout << endl; Pass array name (a) and size to function. Arrays are passed -by-reference. // pass array a to modify. Array by reference modify. Array( a, ARRAYSIZE ); fig 04_14. cpp (2 of 3) cout << "The values of the modified array are: n"; // output modified array for ( int j = 0; j < ARRAYSIZE; j++ ) cout << setw( 3 ) << a[ j ]; // output value of a[ 3 ] cout << "nnn" << "Effects of passing array element by value: " << "nn. The value of a[3] is " << a[ 3 ] << 'n'; a single array element by Pass // pass array element a[ 3 ] by value modify. Element( a[ 3 ] ); value; the original cannot be modified. // output value of a[ 3 ] cout << "The value of a[3] is " << a[ 3 ] << endl; return 0; // indicates successful termination 38 } // end main

52 53 54 55 56 57 58 59 60 61 62 63 64 65

52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 // in function modify. Array, "b" points to // the original array "a" in memory void modify. Array( int b[], int size. Of. Array ) { // multiply each array element by 2 for ( int k = 0; k < size. Of. Array; k++ ) b[ k ] *= 2; Although named b, the array points to the original array a. It can modify a’s data. fig 04_14. cpp (3 of 3) Individual array elements are passed by value, and the originals cannot be changed. // in function modify. Element, "e" is a local copy of // array element a[ 3 ] passed from main void modify. Element( int e ) { // multiply parameter by 2 cout << "Value in modify. Element is " << ( e *= 2 ) << endl; } // end function modify. Array } // end function modify. Element 39

Effects of passing entire array by reference: The values of the original array are:

Effects of passing entire array by reference: The values of the original array are: 0 1 2 3 4 The values of the modified array are: 0 2 4 6 8 fig 04_14. cpp output (1 of 1) Effects of passing array element by value: The value of a[3] is 6 Value in modify. Element is 12 The value of a[3] is 6 40