4 1 Introduction Arrays Structures of related data

  • Slides: 47
Download presentation
4. 1 Introduction • Arrays – Structures of related data items – Static entity

4. 1 Introduction • Arrays – Structures of related data items – Static entity (same size throughout program) • A few types – Pointer-based arrays (C-like) – Arrays as objects (C++)

4. 2 Arrays • Array – Consecutive group of memory locations – Same name

4. 2 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 ] – First element at position 0 • N-element array c c[ 0 ], c[ 1 ] … c[ n - 1 ] – Nth element as position N-1

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

4. 2 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]

4. 3 Declaring Arrays • When declaring arrays, specify – Name – Type of

4. 3 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 • Declaring multiple arrays of same type – Use comma separated list, like regular variables int b[ 100 ], x[ 27 ];

4. 2 array name c is a (pointer) variable c = address of c[0]

4. 2 array name c is a (pointer) variable c = address of c[0] So, address of c[i] =c+i (in fact, c + i * 4) Name that this same Arrays 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

4. 4 Examples Using Arrays • Initializing arrays – For loop • Set each

4. 4 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

1 2 3 // Fig. 4. 3: fig 04_03. cpp // Initializing an array.

1 2 3 // Fig. 4. 3: fig 04_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 ]; fig 04_03. cpp (1 of 2) 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

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)

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

1 2 3 // Fig. 4. 4: fig 04_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 } // end main // indicates successful termination fig 04_04. cpp (1 of 1)

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)

4. 4 Examples Using Arrays • Array size – Can be specified with constant

4. 4 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

1 2 3 // Fig. 4. 5: fig 04_05. cpp // Initialize array s

1 2 3 // Fig. 4. 5: fig 04_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 fig 04_05. cpp (1 of 2) 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 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).

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 // 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)

1 2 3 // Fig. 4. 6: fig 04_06. cpp // Using a properly

1 2 3 // Fig. 4. 6: fig 04_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; fig 04_06. cpp (1 of 1) Proper initialization of const variable. // initialized constant variable 11 12 13 cout << "The value of constant variable x is: " << x << endl; 14 15 return 0; 16 17 // indicates successful termination } // end main The value of constant variable x is: 7 fig 04_06. cpp output (1 of 1)

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

1 2 // Fig. 4. 7: fig 04_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 } // 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 fig 04_07. cpp (1 of 1) fig 04_07. cpp output (1 of 1)

1 2 3 // Fig. 4. 8: fig 04_08. cpp // Compute the sum

1 2 3 // Fig. 4. 8: fig 04_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 // 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 Compute the sum of the elements of the array. fig 04_08. cpp (1 of 1) fig 04_08. cpp output (1 of 1)

Print out a histogram Given an array of integers print out a histogram, with

Print out a histogram Given an array of integers print out a histogram, with the index number, the amount, and stars: Index Number 0 1 2 3 Number in array 7 Stars ****

Print out stars For each element in the array print out index, print out

Print out stars For each element in the array print out index, print out value at index print out stars

1 2 3 // Fig. 4. 9: fig 04_09. cpp // Histogram printing program.

1 2 3 // Fig. 4. 9: fig 04_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 = 10; int n[ array. Size ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 }; fig 04_09. cpp (1 of 2) 16 17 18 cout << "Element" << setw( 13 ) << "Value" << setw( 17 ) << "Histogram" << endl; 19 20 21 22 23 // for each element of array n, output a bar in histogram for ( int i = 0; i < array. Size; i++ ) { Prints asterisks corresponding cout << setw( 7 ) << i << setw( 13 ) to size of array element, << n[ i ] << setw( 9 ); 24 25 26 n[i]. for ( int j = 0; j < n[ i ]; j++ ) cout << '*'; // print one bar

27 28 cout << endl; // start next line of output 29 30 }

27 28 cout << endl; // start next line of output 29 30 } // end outer for structure 31 32 return 0; 33 34 // 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 fig 04_09. cpp (2 of 2) Histogram ********** *********** *********** *

4. 4 Examples Using Arrays • Strings (more in ch. 5) – Arrays of

4. 4 Examples Using Arrays • Strings (more in ch. 5) – Arrays of characters – All strings end with null ('') – Examples • char string 1[] = "hello"; – 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'

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

4. 4 Examples Using Arrays • Input from keyboard char string 2[ 10 ]; 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 (section 5. 12 explains how) • Printing strings – cout << string 2 << endl; • Does not work for other array types – Characters printed until null found

1 2 3 // Fig. 4_12: fig 04_12. cpp // Treating character arrays as

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

24 25 26 // output characters until null character is reached for ( int

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

4. 4 Examples Using Arrays • Recall static storage (chapter 3) – If static,

4. 4 Examples Using Arrays • Recall static storage (chapter 3) – 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

1 2 3 // Fig. 4. 13: fig 04_13. cpp // Static arrays are

1 2 3 // Fig. 4. 13: fig 04_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(); fig 04_13. cpp (1 of 3) // 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 25 } // end main // indicates successful termination

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 46 "; Array data is changed; the modified values stay. contents of array 1 3; j++ ) << j << "] = " j ] += 5 ) << " "; } // end function static. Array. Init fig 04_13. cpp (2 of 3)

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 fig 04_13. cpp int array 2[ 3 ] = { 1, 2, 3 }; (3 of 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 ) << " "; } // end function automatic. Array. Init "; Although the array is changed, it will be destroyed when the function exits and the changes will be lost.

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

4. 5 Passing Arrays to Functions • Specify name without brackets – To pass

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

4. 5 Passing Arrays to Functions • Arrays passed-by-reference – Functions can modify original

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

4. 5 Passing Arrays to Functions • Functions taking arrays – Function prototype •

4. 5 Passing Arrays to Functions • Functions taking arrays – Function prototype • void modify. Array( int b[], int array. Size ); • void modify. Array( int [], int ); – Names optional in prototype • Both take an integer array and a single integer – No need for array size between brackets • Ignored by compiler – If declare array parameter as const • Cannot be modified (compiler error) • void do. Not. Modify( const int [] );

1 2 3 // Fig. 4. 14: fig 04_14. cpp // Passing arrays and

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

26 27 28 29 30 31 32 Pass array name (a) and size to

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

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; } // end function modify. Array Although named b, the array points to the original array a. It can modify a’s data. Individual array elements are passed in function modify. Element, "e" is a local copybyofvalue, and the array element a[ 3 ] passed from main originals cannot be changed. // // void modify. Element( int e ) { // multiply parameter by 2 cout << "Value in modify. Element is " << ( e *= 2 ) << endl; } // end function modify. Element fig 04_14. cpp (3 of 3)

Effects of passing entire array by reference: The values of 0 1 2 3

Effects of passing entire array by reference: The values of 0 1 2 3 The values of 0 2 4 6 the original array are: 4 the modified array are: 8 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 fig 04_14. cpp output (1 of 1)

1 2 3 // Fig. 4. 15: fig 04_15. cpp // Demonstrating the const

1 2 3 // Fig. 4. 15: fig 04_15. cpp // Demonstrating the const type qualifier. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 void try. To. Modify. Array( const int [] ); 9 10 11 12 int main() { int a[] = { 10, 20, 30 }; 13 14 try. To. Modify. Array( a ); 15 16 cout << a[ 0 ] << ' ' << a[ 1 ] << ' ' << a[ 2 ] << 'n'; 17 18 return 0; 19 20 21 } // end main // Array parameter declared as const. Array cannot be modified, even though it is passed byprototype reference. function // indicates successful termination fig 04_15. cpp (1 of 2)

22 23 24 25 26 27 28 29 30 // In function try. To.

22 23 24 25 26 27 28 29 30 // In function try. To. Modify. Array, "b" cannot be used // to modify the original array "a" in main. void try. To. Modify. Array( const int b[] ) { b[ 0 ] /= 2; // error b[ 1 ] /= 2; // error b[ 2 ] /= 2; // error } // end function try. To. Modify. Array d: cpphtp 4_examplesch 04Fig 04_15. cpp(26) : error C 2166: l-value specifies const object d: cpphtp 4_examplesch 04Fig 04_15. cpp(27) : error C 2166: l-value specifies const object d: cpphtp 4_examplesch 04Fig 04_15. cpp(28) : error C 2166: l-value specifies const object fig 04_15. cpp (2 of 2) fig 04_15. cpp output (1 of 1)

39 Vectors 2003 Prentice Hall, Inc. All rights reserved.

39 Vectors 2003 Prentice Hall, Inc. All rights reserved.

40 7. 11 Introduction to C++ Standard Library Class Template vector (Cont. ) •

40 7. 11 Introduction to C++ Standard Library Class Template vector (Cont. ) • vector elements can be obtained as an unmodifiable lvalue or as a modifiable lvalue – Unmodifiable lvalue • Expression that identifies an object in memory, but cannot be used to modify that object – Modifiable lvalue • Expression that identifies an object in memory, can be used to modify the object 2003 Prentice Hall, Inc. All rights reserved.

41 7. 11 Introduction to C++ Standard Library Class Template vector (Cont. ) •

41 7. 11 Introduction to C++ Standard Library Class Template vector (Cont. ) • vector member function at – Provides access to individual elements – Performs bounds checking • Throws an exception when specified index is invalid • Accessing with square brackets does not perform bounds checking 2003 Prentice Hall, Inc. All rights reserved.

Outline 42 • fig 07_26. cpp Using const prevents output. Vector from modifying the

Outline 42 • fig 07_26. cpp Using const prevents output. Vector from modifying the vector passed to it • (1 of 6) These vectors will store ints Function size returns number of elements in the vector 2003 Prentice Hall, Inc. All rights reserved.

Outline 43 • fig 07_26. cpp • (2 of 6) Comparing vectors using !=

Outline 43 • fig 07_26. cpp • (2 of 6) Comparing vectors using != Copying data from one vector to another 2003 Prentice Hall, Inc. All rights reserved. Assigning data from one vector to another

Outline 44 • fig 07_26. cpp Comparing vectors using == • (3 of 6)

Outline 44 • fig 07_26. cpp Comparing vectors using == • (3 of 6) Displaying a value in the vector Updating a value in the vector Function at provides bounds checking 2003 Prentice Hall, Inc. All rights reserved.

Outline 45 • fig 07_26. cpp Display each vector element • (4 of 6)

Outline 45 • fig 07_26. cpp Display each vector element • (4 of 6) Input vector values using cin 2003 Prentice Hall, Inc. All rights reserved.

Outline 46 • fig 07_26. cpp • (5 of 6) 2003 Prentice Hall, Inc.

Outline 46 • fig 07_26. cpp • (5 of 6) 2003 Prentice Hall, Inc. All rights reserved.

Outline 47 • fig 07_26. cpp • (6 of 6) Call to function at

Outline 47 • fig 07_26. cpp • (6 of 6) Call to function at with an invalid subscript terminates the program 2003 Prentice Hall, Inc. All rights reserved.