Fall 2011 October 21-28, 2011 Ghufran Ahmed
Fall 2011 October 21-28, 2011 Ghufran Ahmed
Arrays
An array is a collection of data elements of same type in contiguous memory e.g. list of names, list of scores Easier way to compare and use data than having separate variables for data elements data_type identifier[size]
int arr[3] declares a one-dimensional array named arr with space for 3 integer variables
Variables contiguous in memory; lowest address has first value, next address has second variable value, and so on
Arrays
An individual variable within an array is called an element of the array The elements of an array are not named, and are accessed by the arrays name and their position in the array (indexing or subcripting) Index of first element is zero, index of last element is size-1 e.g. int arr[3] has variables arr[0], arr[1] and arr[2]
size has to be a positive constant (not variable) i.e. cant do: int x = 3; int arr[x]; but can do: int arr[3 * 2]; Number of bytes reserved with int arr[3]; ?
Arrays
An array is an indexed data structure An array stores a collection of variables All variables stored in an array are of the same data type An individual variable within an array is called an element of the array An element of an array is accessed using the array name and an index The name of the array is the address of the first element. The index is the offset
Declaring an array
data_type array_name[size];
allocates memory for size variables index of first element is 0 index of last element is size-1 size must be a constant
Declaring an Array
Example: int list[10];
allocates memory for 10 integer variables index of first element is 0 index of last element is 9 C++ does not perform any bounds checking on arrays
list[0]
list[1]
list[9]
Arrays
Arrays offer convenient means of grouping together several related variables
One- dimensional arrays type var_name[size] int sample[10]; double d[30]; char ch[100];
Initializing Arrays
Arrays can be initialized at the time they are declared.
Examples:
double taxrate[3] = {0.15, 0.25, 0.3}; char word[] = hello; //word has size 6 char list[5] = {h,e,l,l,o}; //list of characters, not a string double vector[100] = {0.0}; //assigns zero to all 100 elements
Initializing Arrays
float f[5]={0.0, 1.0, 2.0, 3.0, 4.0}; // initializes f[0] to 0.0, f[1] to 1.0f[4] to 4.0
Or
float f[5]; f[0]=0.0; f[1]=1.0;
int a[10]={2}; //rest initialized to zero cout << a[0]<< endl << a[5] << endl;
If no size given, allocates as much as the no. of initializers e.g. int a[] = {5, 2, -9}; // and int a[3] = {5, 2, -9}; // are equivalent
Initializing Arrays
for loops used to initialize arrays
#include <iostream.h> int main() { int t, sample[10]; // this reserves 10 integer elements // load the array for(t=0; t<10; ++t) sample[t]=t; // display the array for(t=0; t<10; ++t) cout << sample[t] << ' '; return 0;
Initializing Arrays
int a[5]; Now an indexed variable like a[1] can be used anywhere that a variable of type int can be used int a[5]; cin >> a[4] >> a[2]; cout << a[2] << << a[4] << endl; cin >> a[3] >> a[0]; int max; max = a[3] + a[0]; cout << max << endl; int next; cin >> next; a[1]= next; cout << a[1] << endl; a[3]= 42; cout << a[3] << endl; int student = 2; a[student] = 99; cout << a[student] << << a[2] << endl;
//Reads in 5 scores, displays max_score and shows //how much each score differs from max_score int main() { const int SIZE = 5; int i, score[SIZE], max_score; cout << Enter << SIZE << scores: \n; cin >> score[0]; max_score = score[0]; for (i=1; i<SIZE; i++) { cin >> score[i]; if (score[i] > max_score) max_score=score[i]; } cout << The highest score is: << max_score << endl << Scores & their difference from highest: \n; for (i=0; i<SIZE; i++) { cout << score[i] << off by << (max_score score[i]) << endl; } return 0; }
Initializing Arrays
Useful to give a constant name to the size of array
/*const type modifier*/ const int NUM_EMPLOYEES = 10; int salaries[NUM_EMPLOYEES];
Arrays
Total size of an array in bytes?
Total bytes = number of bytes in type * number of elements e.g. int sample[10]; Has size in bytes = 10 * sizeof(int)
Initializing Arrays
What is wrong with the following? int num=10; int iarray[num];
// ...
a = b; // error -- illegal /*So how do we make the contents of one array same as the other?*/
Cannot assign one array to another; each element must be copied individually
const int ARRAY_SIZE = 5; int a[] = {10, 11, 12, 13, 14}; int main() { int b[ARRAY_SIZE]; for (int i=0; i < ARRAY_SIZE; ++i) b[i] = a[i]; return 0; }
Summarize Arrays
In C++ all arrays are stored in contiguous memory locations An individual element is accessed by use of an index.
An index describes the position of an element within an array. In C++ all arrays have zero as the index of their first element.
Arrays
// find minimum value min_value = list[0]; for(i=0; i<SIZE; i++) { if (min_value>list[i]) { min_value = list[i]; } }
cout << "minimum value: " << min_value << \n;
Arrays
// find maximum value max_value = list[0]; for(i=0; i<SIZE; i++) { if (max_value<list[i]) { max_value = list[i]; } }
cout << "maximum value: " << max_value << '\n';
Arrays
int a[10] = {1,2,3,4,0,3,4,6,7,8}; int x=3; y=1; cout<< a[x+2*y] <<\n;
cout<<Answer= <<a[a[a[4]]]<<\n;
Output?
Sorting an Array
Lots of applications require sorting Algorithm for sorting
int main(void) { const int SIZE = 10; double darray[SIZE] = {34, 5.6, 0.9, 345.7, 54.1, 23.5, 2.5, 6.78, 12.4, 13.9}; int i, j; for (i=0; i<SIZE-1; i++) { for (j=i+1; j< SIZE; j++) { if (darray[i]>darray[j]) { double temp; temp = darray[i]; darray[i] = darray[j]; darray[j] = temp;
} } } //inplace sorting ?
Sorting an Array
return 0;
Sorting an Array
// Using the bubble sort to order an array. int main() { const int SIZE = 10;
int nums[SIZE]; int a, b, t; // give the array some random initial values for(t=0; t<SIZE; t++) nums[t] = rand();
Sorting an Array
// This is the bubble sort. for(a=1; a<SIZE; a++) { for(b=SIZE-1; b>=a; b--) { if (nums[b-1] > nums[b]) { // if out of order exchange elements t = nums[b-1]; nums[b-1] = nums[b]; nums[b] = t; } } } // This is the end of the bubble sort. } // end of main program
Searching
Another Example Sequential Search Binary Search
Two-D Arrays
Row Major, Col Major
row[0]
row[1]
row[2]
in memory
Output: 1 2 5 6 9 10
3 7 11
4 8 12
for(i=0; i<ROWS; ++i) { for(j=0; j<COLS; ++j) { num[i][j] = (i*COLS)+j+1; cout << num[i][j] << ; } cout << \n; } return 0; // output?
Output: 1 2 7 8
3 9
4 10
5 11
6 12
when multidimensional arrays are used, large amounts of memory are consumed.
Multidimensional Array Initialization int sqrs[10][2] = { 1, 1, 2, 4, 3, 9, 4, 16, 5, 25, 6, 36, 7, 49, 8, 64, 9, 81, 10, 100 };
Multidimensional Arrays
int main(void) { const int ALPHABETS = 26; char code[ALPHABETS][2] = { {'a', 'f'}, {'b', 'w'}, {'c', 'x'}, {'d', 'v'}, {'e', 's'}, {'f', 'r'}, {'g', 'q'}, {'h', 'c'}, {'i', 'g'}, {'j', 'h'}, {'k', 'e'}, {'l', 'u'}, {'m', 'b'}, {'n', 'j'}, {'o', 'd'}, {'p', 'k'}, {'q', 't'}, {'r', 'l'}, {'s', 'm'}, {'t', 'n'}, {'u', 'a'}, {'v', 'o'}, {'w', 'p'}, {'x', 'z'}, {'y', 'i'}, {'z', 'y'} };
Multidimensional Arrays
int i; char alpha; cout << "Enter an alphabet: "; cin >> alpha; for(i=0; i< ALPHABETS; i++) { if(code[i][0]==alpha) { cout << "The code of " << alpha << " is "; cout << code[i][1]<<endl; break; } } return 0;
Reference
Dietel & Dietel
Case Study:
Computing Mean, Median and Mode Using Arrays
Mean
Average
Median
Number in middle of sorted list 1, 2, 3, 4, 5 (3 is median)
Mode
Number that occurs most often 1, 1, 1, 2, 3, 3, 4, 5 (1 is mode)
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 27 28 29 30 31 32 33
// Fig. 4.17: fig04_17.cpp // This program introduces the topic of survey data analysis. // It computes the mean, median, and mode of the data. #include <iostream> using std::cout; using std::endl; using std::ios; #include <iomanip> using std::setw; using std::setiosflags; using std::setprecision;
mean( const int [], int ); median( int [], int ); mode( int [], int [], int ); bubbleSort( int[], int ); printArray( const int[], int );
int main() { const int responseSize = 99; int frequency[ 10 ] = { 0 }, response[ responseSize ] = { 6, 7, 8, 9, 8, 7, 8, 9, 7, 8, 9, 5, 9, 8, 7, 8, 6, 7, 8, 9, 3, 9, 8, 7, 7, 8, 9, 8, 9, 8, 9, 7, 6, 7, 8, 7, 8, 7, 9, 8, 7, 8, 9, 8, 9, 8, 9, 7, 5, 6, 7, 2, 5, 3, 9, 4,
8, 7, 8, 8, 9, 5, 6,
9, 8, 7, 9, 2, 3, 4,
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
7, 8, 9, 6, 8, 7, 8, 9, 7, 8, 7, 4, 4, 2, 5, 3, 8, 7, 5, 6, 4, 5, 6, 1, 6, 5, 7, 8, 7 }; mean( response, responseSize ); median( response, responseSize ); mode( frequency, response, responseSize ); return 0; } void mean( const int answer[], int arraySize ) { int total = 0; cout << "********\n Mean\n********\n";
for ( int j = 0; j < arraySize; j++ ) total += answer[ j ]; cout << << << << << << << << << } void median( int answer[], int size ) { cout << "\n********\n Median\n********\n" "The mean is the average value of the data\n" "items. The mean is equal to the total of\n" "all the data items divided by the number\n" "of data items (" << arraySize "). The mean value for\nthis run is: " total << " / " << arraySize << " = " setiosflags( ios::fixed | ios::showpoint ) setprecision( 4 ) static_cast< double >( total ) / arraySize << "\n\n";
68 69 70 71 72 73 74 75 76 77
<< "The unsorted array of responses is"; printArray( answer, size ); bubbleSort( answer, size ); cout << "\n\nThe sorted array is"; printArray( answer, size ); cout << "\n\nThe median is element " << size / 2 << " of\nthe sorted " << size << " element array.\nFor this run the median is " << answer[ size / 2 ] << "\n\n";
78 }
79 80 void mode( int freq[], int answer[], int size ) 81 { 82 83 84 85 86 87 88 89 90 91 92 93 94 95 for ( int j = 0; j < size; j++ ) ++freq[ answer[ j ] ]; for ( rating = 1; rating <= 9; rating++ ) freq[ rating ] = 0; cout << "\n********\n Mode\n********\n"; int rating, largest = 0, modeValue = 0;
Notice how the subscript in frequency[] is the value of an element in response[] (answer[]).
cout << "Response"<< setw( 11 ) << "Frequency" << setw( 19 ) << "Histogram\n\n" << setw( 55 ) << "1 << "5 1 0 2 5 2\n" << setw( 56 ) 0 5\n\n";
98
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 }
cout << "The mode is the most frequent value.\n" << "For this run the mode is " << modeValue
114
115 } 116
<< " which occurred " << largest << " times." << endl;
117 void bubbleSort( int a[], int size ) 118 { 119 120 int hold;
121 122 123 124 125 126 127 128 129 130 } 131
132 void printArray( const int a[], int size ) 133 { 134 135 136 137 138 139 cout << setw( 2 ) << a[ j ]; if ( j % 20 == 0 ) cout << endl; for ( int j = 0; j < size; j++ ) {
140
141 }
******** Mean ******** The mean is the average value of the data items. The mean is equal to the total of all the data items divided by the number of data items (99). The mean value for this run is: 681 / 99 = 6.8788
array 8 9 8 8 7 8 9 8 9 9 4 6 8 7 5
of responses is 9 7 8 9 5 9 8 7 7 7 8 9 8 9 8 9 2 7 8 9 8 9 8 9 4 7 8 9 6 8 7 8 6 4 5 6 1 6 5 7
8 7 7 9 8
7 8 5 7 7
8 9 3 8
array 3 3 3 6 6 6 7 7 7 8 8 8 9 9 9
is 4 4 6 6 7 7 8 8 9 9
4 7 7 8 9
4 7 7 8 9
4 7 7 8 9
5 7 8 8 9
4. Program Output
5 7 8 8 9
5 7 8 8 9
5 7 8 8 9
5 7 8 8 9
5 7 8 8 9
5 7 8 8
The median is element 49 of the sorted 99 element array. For this run the median is 7
Frequency
Histogram
1 0 1 5 2 0 2 5
1 1 * 2 3 *** 3 4 **** 4 5 ***** 5 8 ******** 6 9 ********* 7 23 *********************** 8 27 *************************** 9 19 ******************* The mode is the most frequent value. For this run the mode is 8 which occurred 27 times.
Program Output