Académique Documents
Professionnel Documents
Culture Documents
Arrays
Structures of related data items Static entity (same size throughout program)
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 ]
Array
c[0]
c[1] c[2] c[3] c[4] c[5] c[6]
-45
6 0 72 1543 -89 0
c[7]
c[8] c[9] c[10] c[11]
62
-3 1 6453 78
When
Declaring
Initializing
arrays
For loop
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
// code 1 // Initializing an array. #include <iostream> using std::cout; using std::endl; #include <iomanip> using std::setw; int main() {
Declare a 10-element array of integers. Initialize array to 0 using a for loop. Note that the array has elements n[0] to n[9].
int n[ 10 ]; // n is an array of 10 integers // 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; return 0; // indicates successful termination
} // end main
Element 0 1 2 3 4 5 6 7 8 8 9
Value 0 0 0 0 0 0 0 0 0 0
// code 2
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
// Initializing an array with a declaration. #include <iostream> using std::cout; using std::endl; #include <iomanip> using std::setw;
Note the use of 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;
the initializer
// 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
Element 0 1 2 3 4 5 6 7 8
Value 32 27 64 18 95 14 90 70 60
9
Array
size
Constants cannot be changed Constants must be initialized when declared Also called named constants or read-only variables
10
Write
a C++ program that displays even integers from 2-20 Using arrays
1-11
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
// code 3 // Initialize array s to the even integers from 2 to 20. #include <iostream> using std::cout; using std::endl; #include <iomanip> using std::setw; int main() {
Note use of const keyword. Only const variables can // constant variable can be used to specify array size specify array sizes. const int arraySize = 10; The program becomes more scalable when we set the int s[ arraySize ]; // array s has 10 elements array size using a const variable. We can change for ( int i = 0; i < arraySize; i++ ) // set the values arraySize, and all the loops s[ i ] = 2 + 2 * i; will still work (otherwise, wed have to update every cout << "Element" << setw( 13 ) << "Value" << endl; in the program). loop
// 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
26
} // end main
Element 0 1 2 3 4 5 6 7 8 9 12
Value 2 4 6 8 10 12 14 16 18 20
Write
of
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 Using array
1-13
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// code 6 // 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; // indicates successful termination } // end main
19
20 21 22 23 24
14
Write
Element 0 1 2 3 4 5 6 7 8 9
Value 19 3 15 7 11 9 13 5 17 1
Histogram ******************* *** *************** ******* *********** ********* ************* ***** ***************** *
1-15
// code 7
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 27 28 29 30 31
32
16
Suppose
a dice has been rolled 6000 times. Determine how many times it showed
1-17
1 2 3
// code 8 // Roll a six-sided die 6000 times. #include <iostream> using std::cout; using std::endl; #include <iomanip> using std::setw; #include <cstdlib> #include <ctime> int main() { const int arraySize = 7;
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
24
This creates a number between 1 and 6, which determines the index of frequency[] that should be incremented.
25
28 29 30 31 32
// output frequency elements 1-6 in tabular format for ( int face = 1; face < arraySize; face++ ) cout << setw( 4 ) << face << setw( 13 ) << frequency[ face ] << endl;
33
Face 1 2 3 4 5 6
Strings
char string1[] = { 'h', 'e', 'l', 'l', 'o', '\0 }; String1[ 0 ] is 'h' string1[ 2 ] is 'l'
19
Input
from keyboard
Printing
strings
1 // code 10 2 // Treating character arrays as strings. 3 #include <iostream> 4 using std::cout; 5 using std::cin; 6 using std::endl; Two different ways to declare 7 int main() strings. string2 is initialized, 8 { and its size determined 9 char string1[ 20 ], // reserves 20 characters automatically . 10 char string2[] = "string literal"; // reserves 15 characters Examples of reading strings 11 12 // read string from user into array string2 from the keyboard and 13 cout << "Enter the string \"hello there\": "; printing them out. 14 cin >> string1; // reads "hello" [space terminates input] 15 16 // output strings 17 cout << "string1 is: " << string1 18 << "\nstring2 is: " << string2; 19 20 cout << "\nstring1 with spaces between characters is:\n"; 21 22 // output characters until null character is reached 23 for ( int i = 0; string1[ i ] != '\0'; i++ ) 24 cout << string1[ i ] << ' '; Enter the the characters in Can accessstring "hello there": hello there 25 string1 is: hello a string using array notation. 26 cin >> string1; // reads "there" string2 ends when the The loopis: string literal 27 cout << "\nstring1 is: " << string1 << endl; string1 with spaces between characters is: null character is found. 28 h e l l o 29 return 0;} // indicates successful termination string1 is: there
21
Sorting
data
Important computing application Virtually every organization must sort some data
Bubble
Several passes through the array Successive pairs of elements are compared
22
Example:
3 3 2 2 2
4 2 3 3 3
2 4 4 4 4
7 6 6 6 6
Swapping
y = x; x = y;
variables
int x = 3, y = 4;
What
happened?
Solution
int x = 3, y = 4, temp = 0; temp = x; x = y; y = temp; // temp gets 3 // x gets 4 // y gets 3
24
1 2 3
// This program sorts an array's values into ascending order. #include <iostream> using std::cout;
4 using std::endl; 5 #include <iomanip> 6 7 int main() 8 { 9 const int arraySize = 10; // size of array a 10 int a[ arraySize ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 }; 11 int hold; // temporary location used to swap array elements 12 13 cout << "Data items in original order\n"; 14 15 // output original array 16 for ( int i = 0; i < arraySize; i++ )
17 cout << setw( 4 ) << a[ i ];
16 27 29 31 34 35 36 38 18 20 21 22 24 26 28
for ( int pass = 0; pass < arraySize - 1; pass++ ) If // loop to control number of comparisons per pass the element on the left for ( int j = 0; j < arraySize pass - 1; j++ ) (index j) is larger than the if ( a[ j ] > a[ j + 1 ] ) { element on the right hold = a[ j ]; (index j + 1), then we a[ j ] = a[ j + 1 ]; swap them. Remember the a[ j + 1 ] = hold; need of a temp variable. } // end if cout << "\nData items in ascending order\n; // output sorted array for ( int k = 0; k < arraySize; k++ ) Data items in original order cout << setw( 4 ) << a[ k ]; 2 6 4 8 10 12 89 68 45 cout << endl; return 0; // indicates successful termination Data items in ascending order } // end main 2 4 6 8 10 12 37 45 68 25
37 89
Search
Start at one end, go to other Inefficient If search key not present, examines every element
26
1 3 5
6 7 11 12 13 14 15 16 17 18 20 21 22 23 25 28 29 30 47 48
using std::cin; using std::endl; int main() { const int arraySize = 100; // size of array a int a[ arraySize ]; // create array a int searchKey; // value to locate in a
for ( int i = 0; i < arraySize; i++ ) // create some data a[ i ] = 2 * i; cout << "Enter integer search key: "; cin >> searchKey; // attempt to locate searchKey in array a
if ( a[ i ] == searchkey ) cout << "Found value " << endl; else cout << "Value not found" << endl;
} // end function linearSearch
27
Binary
search
Only used with sorted arrays Compare middle element with key
If equal, match found If key < middle Repeat search on first half of array If key > middle Repeat search on last half At most log2N steps, where N is the # of elements 30 element array takes at most 5 steps 2 > 30
28
Very fast
Multiple
subscripts
a[ i ][ j ] Tables with rows and columns Specify row, then column Array of arrays
a[0] is an array of 4 elements a[0][0] is the first element of that array Column 0 Column 1 Column 2 Column
a[ 0 ][ 0 ] a[ 1 ][ 0 ] a[ 2 ][ 0 ] a[ 0 ][ 1 ] a[ 1 ][ 1 ] a[ 2 ][ 1 ] a[ 0 ][ 2 ] a[ 1 ][ 2 ] a[ 2 ][ 2 ]
3 a[ 0 ][ 3 ]
a[ 1 ][ 3 ] a[ 2 ][ 3 ]
To
initialize
1 3 2 4
int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
Row 0 Row 1
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };
1 3 0 4
30
Referenced
like normal
cout << b[ 0 ][ 1 ];
Function
prototypes
31
1 // code 18 2 // Initializing multidimensional arrays. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 9 int main() 10 { 11 int array1[ 2 ][ 3 ] = { { 1, 2, 3 }, { 4, 5, 6 } }; 12 13 14 cout << "Values in array1 by row are:" << endl; 15 for ( int i = 0; i < 2; i++ ) { // for each row 16 17 for ( int j = 0; j < 3; j++ ) // output column values 18 cout << a[ i ][ j ] << ' << endl; 19 return 0; // indicates successful termination 20 21 } // end main
32
1-33
using namespace std; int main() { const int size =5; int value[size] = (1, 2, 3); double junk[size]; cout<<end1; for(int i=0; i<size ; i++) cout<< << setw(12)<<values[i]; cout<<end1; for(int i=0; i<size ; i++) cout<< << setw(12)<<junk[i]; cout<<end1; return 0; }
1-34
#include <iostream> using namespace std; int bill [] = {16, 2, 77, 40, 12071}; int n, result=0; int main () { for ( n=0 ; n<5 ; n++ ) { result += bill[n]; } cout << result; return 0; }
12206
1-35
#include <iostream> using namespace std; int main() { const int max = 10; int number[max]; int sum = 0; cout << "Please type 10 integers.\n"; for( int i = 0; i < max; i++ ) { cout << "Number " << i + 1 << ": "; cin >> number[i]; sum += number[i]; } cout << "\n\nThe sum of these numbers is " << Sum << "\n\n"; return 0;}
1-36
Read
the entries of an array of 10 integers from a user. Compute x as the average of the 10 entries and then compute the average of those entries that are greater than or equal to x. Print this final average.
1-37
#include <iostream> using namespace std; int main() { int a[10], c, count = 0; double total1 = 0, average1, total2 = 0, average2; cout << "Enter 10 integers for the array" << endl; for (c = 0; c < 10; c++) { cin >> a[c]; for (c = 0; c < 10; c++) { total1 += a[c]; } } average1 = total1 / 10; for (c = 0; c < 10; c++) if (a[c] >= average1) { total2 += a[c]; count++; } average2 = total2 / count; cout << average2 << endl; return 0; }
1-38