Arrays
Arrays
Arrays
1 Arrays
Introduction
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 Array
Arrays
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 ]
4.2
Arrays
4.2
Name that this same c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11]
Arrays
of array (Note all elements of array have the name, c) -45 6 0 72 1543 -89 0 62 -3 1 6453 78
4.3
Declaring Arrays
4.4
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
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: fig04_03.cpp // Initializing an array. #include <iostream> using std::cout; using std::endl; #include <iomanip>
fig04_03.cpp (1 of 2)
using std::setw;
int main() { int n[ 10 ];
// initialize elements of array for ( int i = 0; i < 10; i++ ) n[ i ] = 0; // set element at location i to 0
to 0 using a for loop. Note that the array nhas elements n[0] to n[9]. 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;
26 27 28
Element 0 1 2 3 4 5 6 7 8 9
Value 0 0 0 0 0 0 0 0 0 0
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: fig04_04.cpp // Initializing an array with a declaration. #include <iostream> using std::cout; using std::endl; #include <iomanip>
fig04_04.cpp (1 of 1)
using std::setw;
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; // 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;
} // end main
Element 0 1 2 3 4 5 6 7 8 9
Value 32 27 64 18 95 14 90 70 60 37
fig04_04.cpp output (1 of 1)
Constants cannot be changed Constants must be initialized when declared Also called named constants or read-only variables
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: fig04_05.cpp // Initialize array s to the even integers from 2 to 20. #include <iostream> using std::cout; using std::endl; #include <iomanip>
fig04_05.cpp (1 of 2)
using std::setw;
int main() Only const variables { // constant variable can be used to specify array sizes. specify array size const int arraySize = 10; int s[ arraySize ]; // array s
The program becomes more scalable has 10 elements when we set the array size using a const variable. i++ ) // We can change arraySize, set the values and all the loops will still work (otherwise, wed have << "Value" << endl; to update every loop in the program).
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; } // end main Value 2 4 6 8 10 12 14 16 18 20 // indicates successful termination
Element 0 1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// Fig. 4.6: fig04_06.cpp // Using a properly initialized constant variable. #include <iostream> using std::cout; using std::endl; int main() { const int x = 7;
fig04_06.cpp output (1 of 1)
cout << "The value of constant variable x is: " << x << endl; return 0; } // end main // indicates successful termination
1 2 3 4 5 6 7 8 9 10 11 12
// Fig. 4.7: fig04_07.cpp // A const object must be initialized. int main() { const int x; x = 7;
// Error: x
Uninitialized const results in a syntax error. Attempting to modify the const is must be initialized another error.
return 0;
} // end main
d:\cpphtp4_examples\ch04\Fig04_07.cpp(6) : error C2734: 'x' : const object must be initialized if not extern d:\cpphtp4_examples\ch04\Fig04_07.cpp(8) : error C2166: l-value specifies const object
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: fig04_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; 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; } // end main // indicates successful termination
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 ********
For each element in the array print out index, print out value at index print out stars
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: fig04_09.cpp // Histogram printing program. #include <iostream> using std::cout; using std::endl; #include <iomanip>
fig04_09.cpp (1 of 2)
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].
27 28 29 30 31 32 33 34
} // end outer for structure return 0; } // end main Value 19 3 15 7 11 9 13 5 17 1 Histogram ******************* *** *************** ******* *********** ********* ************* ***** ***************** * // indicates successful termination
Element 0 1 2 3 4 5 6 7 8 9
In Class Assignment The Rutgers Student Council (RSC) is conducting a poll of who should be the next apprentice. There are 10 candidates to choose from. The RSC has polled 1000 students on campus.
You are to write a program that tallies up the number of votes each candidate received and pronounces a winner.
Recording the votes Every time a person votes, the votes are recorded
Outline of Program 1. Input votes that were collected and store in array votes 2. Tally up frequency of votes for each candidate. 3. Determine which candidate has the most number of votes. 4. Print out the winner
Step 1: Input votes that were collected and store in array. Have to have this to have a record of the votes (just in case).
for(I = 0; I < 1000; i++) cin >> votes[i];
CUMBERSOME!!!!
And not scalable!!
Use an array called frequency which contains 10 elements one for each candidate: int frequency[XX];
Votes: 1 5 10 10 10 5 6 7 6 7 6 7 6 7 10 10 10 10 10 1 Etc..
int frequency[11];
Frequency
1 2 3 4 5 6 7 8 9 10
2 0 0 0 2 4 4 0 0 8
for(i =0; i < 1000; i++) if (votes[i] == 1) frequency[1]++; else if (votes[i] == 2) frequency[2]++; else if (votes[i] == 3) frequency[3]++; IS THERE A BETTER WAY?
YES!!!!
++frequency[ votes[ i ] ]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Fig. 4.11: fig04_11.cpp // Student poll program. #include <iostream> using std::cout; using std::endl; #include <iomanip>
fig04_11.cpp (1 of 2)
using std::setw;
int main() { // define array sizes
const int responseSize = 1000; int vote[responseSize]; // size of array responses 16 const int frequencySize = 11; // size of array frequency 17 18 // place survey responses in the array votes 19 For (int i = 0; i < 1000; i++){ cout <<Please enter the next vote << endl; cin >> vote[i]; } // initialize frequency counters to 0 int frequency[ frequencySize ] = { 0 };
22 23 24 25
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[ votes[answer] ]; // display results cout << "Rating" << setw( 17 ) << "Frequency" << endl;
// 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 printmax(frequency); } // end main
fig04_11.cpp (2 of 2) responses[answer] is the rating (from 1 to 10). This determines the index in frequency[] to increment.
Rating 1 2 3 4 5 6 7 8 9 10
Frequency 991 1 1 1 1 1 1 1 1 1
fig04_11.cpp output (1 of 1)
Find winner int printmax(int frequency[], frequencysize) { int max = 0, winner = 0; for (int i = 0; i < frequencysize; i++) if (frequency[i] > max) { max = frequency[i]; Need to store the actual winner not just the number winner = i; of votes the winner has!!! } cout << and the next apprentice is << i <<endl;
4.4
4.4
Printing strings
cout << string2 << endl;
Does not work for other array types
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_12: fig04_12.cpp // Treating character arrays as strings. #include <iostream> using std::cout; using std::cin; using std::endl; int main() { char string1[ 20 ], char string2[] = "string literal"; // reserves 15 characters // read string cout << "Enter cin >> string1;
fig04_12.cpp (1 of 2) Two different ways to declare strings. string2 is initialized, and its size // reserves 20 characters determined automatically .
Examples of reading strings from user into array string2 from the keyboard and the string \"hello there\": ";out. printing them
// reads "hello" [space terminates input]
// output strings cout << "string1 is: " << string1 << "\nstring2 is: " << string2; cout << "\nstring1 with spaces between characters is:\n";
24 25 26 27 28 29 30 31 32 33
// output characters until null character is reached for ( int i = 0; string1[ i ] != '\0'; i++ ) cout << string1[ i ] << ' '; cin >> string1; // reads "there" string cout << "\nstring1 is: " << string1 << endl; return 0; // indicates successful
Can access the characters in a fig04_12.cpp using array notation. (2 of 2) The loop ends when the null character is found. fig04_12.cpp termination output (1 of 1)
} // end main
Enter the string "hello there": hello there string1 is: hello string2 is: string literal string1 with spaces between characters is: h e l l o string1 is: there
4.4
If not static
Created (and destroyed) in every function call
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: fig04_13.cpp // Static arrays are initialized to zero. #include <iostream> using std::cout; using std::endl; void staticArrayInit( void ); void automaticArrayInit( void ); // function prototype // function prototype
fig04_13.cpp (1 of 3)
int main() { cout << "First call to each function:\n"; staticArrayInit(); automaticArrayInit(); cout << "\n\nSecond call to each function:\n"; staticArrayInit(); automaticArrayInit(); cout << endl; return 0; } // end main // indicates successful termination
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 Static array, initialized to zero void staticArrayInit( void ) on first function call. { // initializes elements to 0 first time function is called static int array1[ 3 ]; cout << "\nValues on entering staticArrayInit:\n"; // output contents of array1 for ( int i = 0; i < 3; i++ ) cout << "array1[" << i << "] = " << array1[ i ] << " cout << "\nValues on exiting staticArrayInit:\n"; // modify and output for ( int j = 0; j < cout << "array1[" << ( array1[ contents of array1 3; j++ ) << j << "] = " j ] += 5 ) << " ";
fig04_13.cpp (2 of 3)
";
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 automaticArrayInit( void ) Automatic { with every // initializes elements each time function is called int array2[ 3 ] = { 1, 2, 3 }; cout << "\n\nValues on entering automaticArrayInit:\n"; // output contents of array2 for ( int i = 0; i < 3; i++ ) cout << "array2[" << i << "] = " << array2[ i ] << " cout << "\nValues on exiting automaticArrayInit:\n"; // modify and output for ( int j = 0; j < cout << "array2[" << ( array2[ contents of array2 3; j++ ) << j << "] = " j ] += 5 ) << " ";
";
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 array1[0] Values on array1[0] Values on array2[0] Values on array2[0] entering staticArrayInit: = 0 array1[1] = 0 array1[2] = 0 exiting staticArrayInit: = 5 array1[1] = 5 array1[2] = 5 entering automaticArrayInit: = 1 array2[1] = 2 array2[2] = 3 exiting automaticArrayInit: = 6 array2[1] = 7 array2[2] = 8
fig04_13.cpp output (1 of 1)
Second call to each function: Values on array1[0] Values on array1[0] Values on array2[0] Values on array2[0] entering staticArrayInit: = 5 array1[1] = 5 array1[2] = 5 exiting staticArrayInit: = 10 array1[1] = 10 array1[2] = 10 entering automaticArrayInit: = 1 array2[1] = 2 array2[2] = 3 exiting automaticArrayInit: = 6 array2[1] = 7 array2[2] = 8
4.5
4.5
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
4.5
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: fig04_14.cpp // Passing arrays and individual array elements to functions. #include <iostream> using std::cout; using std::endl; #include <iomanip>
using std::setw;
void modifyArray( int [], int ); void modifyElement( int );
cout << "Effects of passing entire array by reference:" << "\n\nThe values of the original array are:\n";
// output original array for ( int i = 0; i < arraySize; i++ ) cout << setw( 3 ) << a[ i ];
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
Pass array name (a) and size to function. Arrays are by reference passed-by-reference.
fig04_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 << "\n\n\n" << "Effects of passing array element by value:" << "\n\nThe value of a[3] is " Pass a single array element << a[ 3 ] << '\n'; // pass array element a[ 3 ] by modifyElement( a[ 3 ] );
// output value of a[ 3 ] cout << "The value of a[3] is " << a[ 3 ] << endl; return 0; } // end main // indicates successful termination
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
// in function modifyArray, "b" points to // the original array "a" in memory void modifyArray( int b[], int sizeOfArray ) { // multiply each array element by 2 for ( int k = 0; k < sizeOfArray; k++ ) b[ k ] *= 2;
Although named b, the array points to the original array a. It can modify as data. fig04_14.cpp (3 of 3)
Individual array elements are passed by value, and the in function modifyElement, "e" is a local copy of array element a[ 3 ] passed from main originals cannot be changed.
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
fig04_14.cpp output (1 of 1)
Effects of passing array element by value: The value of a[3] is 6 Value in modifyElement is 12 The value of a[3] is 6
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
// Fig. 4.15: fig04_15.cpp // Demonstrating the const type qualifier. #include <iostream> using std::cout; using std::endl; void tryToModifyArray( const int [] ); //
Array parameter declared as const. Array cannot be modified, even though it is passed by reference. function prototype
fig04_15.cpp (1 of 2)
22 23 24 25 26 27 28 29 30
// In function tryToModifyArray, "b" cannot be used // to modify the original array "a" in main. void tryToModifyArray( const int b[] ) { b[ 0 ] /= 2; // error b[ 1 ] /= 2; // error b[ 2 ] /= 2; // error } // end function tryToModifyArray
d:\cpphtp4_examples\ch04\Fig04_15.cpp(26) : error C2166: l-value specifies const object d:\cpphtp4_examples\ch04\Fig04_15.cpp(27) : error C2166: l-value specifies const object d:\cpphtp4_examples\ch04\Fig04_15.cpp(28) : error C2166: l-value specifies const object