2.27k likes | 4.88k Views
C++ Arrays. Agenda. What is an array? Declaring C++ arrays Initializing one-dimensional arrays Reading and Writing one-dimensional arrays Passing one-dimensional arrays to functions Manipulating one-dimensional arrays: Searching for something Rearranging stored values
E N D
Agenda • What is an array? • Declaring C++ arrays • Initializing one-dimensional arrays • Reading and Writing one-dimensional arrays • Passing one-dimensional arrays to functions • Manipulating one-dimensional arrays: • Searching for something • Rearranging stored values • Computing and storing series of values
What Is An Array? • An array is a collection of values that have the same data type, e.g. • A collection of int data values or • A collection of bool data values • We refer to all stored values in an array by its name • If we would like to access a particular value stored in an array, we specify its index (i.e. its position relative to the first array value) • The first array index is always 0 • The second value is stored in index 1 • Etc.
How To Declare Arrays • To declare an array in C++, you should specify the following things • The data type of the values which will be stored in the array • The name of the array (i.e. a C++ identifier that will be used to access and update the array values) • The dimensionality of the array: • One dimensional (i.e. list of values ), • Two-dimension array (a matrix or a table), etc. • The size of each dimension • Examples • int x[10]; // An integer array named x with size 10 • float GPA[30]; // An array to store the GPA for 30 students • int studentScores[30][5]; // A two-dimensional array to store the scores of 5 exams for 30 students
One-dimensional Arrays • We use one-dimensional (ID) arrays to store and access list of data values in an easy way by giving these values a common name, e.g. int x[4]; // all values are named x x[0] = 10; // the 1st value is 10 x[1] = 5; // the 2nd value is 5 x[2] = 20; // the 3rd value is 20 x[3] = 30; // the 4th value is 30 x[0] x[1] x[2] x[3] 10 5 20 30
Array Indices and Out-of-bound Run-time Error • All C++ one-dimensional arrays with N entries start at index 0 and ended at index N-1 const int N=5; int v[N]; // this array contains 5 entries • It is a common error to try to access the Nth entry, e.g. v[5] or V[N], since the index of the last array entry is N-1, not N
Initializing One-dimensional Arrays • There are two common ways to initialize one-dimensional arrays • Using for loop, e.g. int x[10]; for( int index=0; index<10; index++) x [index] = index+1 ; • Specifying list of values while declaring the 1D array, e.g. int x[10] = {1,2,3,4,5,6,7,8,9,10}; int y[ ] = {0,0,0}; // this array contains 3 entries with 0 values double z[100] = {0}; // this array contains 100 // entries, all of which are initialized by 0 double w[20] = {5,3,1}; // this array contains 20 entries, // the first three entries are initialized by 5, 3, and1 respectively // while the remaining 17 entries are automatically initialized by 0 bool pass[10] = {true, true}; // this array contains 10 entries. // The first two entries are initialized to true, while the remaining 8 // entries are automatically initialized to false
Storing Values in 1D Arrays • Wrong way: Int x[10]; cin >> x; // you cannot do that unless you // overload the >> operator! // Wait until you take CSCI-110 • Correct way: int x[10]; // Reading one value at a time from the user: for (int index=0; index<10; index++) cin >> x[index];
Displaying Values Stored in 1D Arrays • Wrong way: Int x[10]; cout << x;// you cannot do that unless you // overload the << operator! // Wait until you take CSCI-110 • Correct way: int x[10]; // Displaying one value per line to the user: for (int index=0; index<10; index++) cout << x[index] << endl;
Example: Read Values and Print them in Reverse Order #include <iomanip.h> void main() { int x[5], index; cout << “Please enter five integer values: “; for( index=0; index<5; index++) cin >> x[index]; cout << “The values in reverse order are: “; for (index=4; index>=0; index--) cout << setw(3) << x[index]; cout << endl; }
Passing 1D Arrays to Functions • By default, arrays are passed to functions by reference even though we do not even write the reference operator (&) in front of the array name, why? • Since arrays store huge number of values, it is much faster and more economical to pass arrays by reference instead of wasting the time and memory copying the values of the arrays into another arrays • Example • The following function signature accepts an array x as a reference parameter and it also accepts the number of entries in the array (i.e. its size) void process (int x[], int size);
Passing 1D Arrays to Functions • Why don’t we use the following signature to pass an array to a function? void process (int x[10]); • Unfortunately, using the above signature means that this particular function will only process a 1D array with size =10 (no more no less!) • Of course we would like to write a function to handle different array sizes and that is why we use the following signature instead void process (int x[ ], int size); • Visual Studio in particular does not issue any warnings or syntax error if you use the first signature and pass different array size, but other compliers do!
#include <iomanip> #include <iostream> #include <string> using namespace std; void display (string prompt, int x[ ], int n) { cout << prompt ; for (int i=0; i<n; i++) cout << setw(3) << x[i]; cout << endl; } void main() { int v[7] = {1,2,3,4}; int w[4] = {10,20,30,40}; display ("The values of v array : ", v, 7); display ("The values of w array : ", w, 4); } Example 2: Passing 1D Array to A Function
Passing 1D Arrays As const Reference Parameters • It is a good idea to pass arrays as const reference parameters if you want to assure that the functions will never change the values stored in the arrays, e.g. void display (const int x[ ] , int size) { for (int i=0; i<size; i++) cout << x[i] << endl; }
Array Manipulation I. Searching for Something…
Example: Searching for the smallest value in an array int smallest (const int x[ ], int n) { /* Assume for a moment that x[0] contains the smallest value */ int min = x[0]; for (int i=1; i<n; i++) if (min>x[i]) min = x[i]; return min; }
Example: Searching for The Index of The Smallest Value in An Array int min_index (int x[ ], int size, int start=0) { int index = start; int min = x[index]; for (int i=index+1; i<size; i++) if (min>x[i]) { min = x[i]; index = i; } return index; } • Notice that: • The array is not sorted! • We use the parameter start to specify the start searching index. The 0 is the default value of this parameter • Later on, we will use this function to sort an array
Example: Searching for A Key in Unsorted Array Using Sequential Search int seqSearch (int x[ ], int size, int key) { for (int i=0; i<size; i++) if (key == x[i]) return i; return -1; } This function will return the index of the first value that equals to the key if exists, otherwise, it returns -1
Example: Searching for A Key in A Sorted Array Using Binary Search int bSearch (int x[ ],int n,int key) { int left=0, right=n-1; do { int mid = (left+right)/2; if (x[mid] == key) return mid; if (x[mid]<key) right=mid-1; else left=mid+1; } while (left<=right); return -1; } • NB. • The array x must be sorted! • Each loop iteration eliminate half of the current length of the array which makes this searching technique more faster than the sequential search • We stop searching when left>right and in this case we return with -1 to indicate that we could not find the key in the array
Array Manipulation II. Compute Something…
Example: Compute The Sum of Values Stored in An Array int sum (const int x[ ], int n) { int s = 0; for (int i=0; i<n; i++) s+=x[i]; return s; }
Example: Compute The Mean Value of An Array double mean (const int x[ ], int n) { return (double) sum(x,n) / n; }
Example: Compute The Standard Deviation of An Array double stdiv (const int x[ ], int x) { double ss = 0.0 , xBar = mean(x,n); for(int i=1; i<n; i++) ss+=pow(x[i]-xBar,2); if (n<30) return sqrt(ss/(n-1)); else return sqrt(ss/n); }
Example: Compute The Range of Numbers int range (const int x[ ], int n) { return max (x, n) – min (x, n); }
Example: Compute The Median double median( double x[], int n) { sort (x, n); //assume sort( ) is already defined if (n % 2 == 1) return x[n/2+1]; else return (x[n/2]+x[n/2+1)/2; }
Example: Multiplying An Array with A Constant Value void multiply( int x[ ], int n, const int value) { for (int i=0; i<n; i++) x[i] *= value; }
Example: Dot Product of Two Arrays int dotProduct( int x[ ], int y[ ], int n) { int sum = 0; for (int i=0; i<n; i++) sum += x[i] * y[i]; return sum; }
Example: Adding/Subtracting Two arrays void add (const int x[], const int y[], int z[], nt n) { for (int i=0; i<n; i++) z[i] = x[i] + y[i]; } void subtract (const int x[], const int y[], int z[], int n) { for (int i=0; i<n; i++) z[i] = x[i] - y[i]; }
Example: Set Intersection void intersection (const int set1[], int size1, const int set2[], int size2, int s[], int &size) { size=0; for(int i=0; i<size1; i++) if (seqSearch(set2, size2, set1[i])>-1) set[size++] = set1[i]; }
Example: Set Difference void difference (const int set1[], int size1, const int set2[], int size2, int s[], int &size) { size=0; for(int i=0; i<size1; i++) if (seqSearch(set2, size2, set1[i]) == -1) set[size++] = set1[i]; }
Example: Set Union void union (const int set1[], int size1, const int set2[], int size2, int s[], int &size) { size = size1; for(int i=0; i<size; i++) set[i]=set1[i]; for(int i=0; i<size2; i++) if (seqSearch(set, size, set2[i]) == -1) set[size++] = set2[i]; }
#include <iomanip.h> void main() { short int binary[64]={0}; int index, bits=0; unsigned int n; cout << "Please enter an integer value: "; cin >> n; cout << "The binary number is "; if (n==0) cout << 0 << endl; else { while (n>0) { binary[bits] = n % 2; n /= 2; bits++; } for (index=bits-1;index>=0;index--) cout << binary[index]; cout << endl; } } Example: Converting An Integer Decimal Number to Binary Number Guess what happens when you enter -1!
#include <iomanip.h> void main() { short int binary[64]={0}; int index, bits=0; unsigned int n; cout << "Please enter an integer value: "; cin >> n; cout << "The binary number is "; if (n==0) cout << 0 << endl; else { while (n>0) { binary[bits] = n % 2; n /= 2; bits++; } for (index=bits-1;index>=0;index--) cout << binary[index]; cout << endl; } } Example #2: Converting an integer decimal number to binary number Guess what happens when you enter -1!
Example 4: Search for The Largest Value in 1D Array #include <iostream.h> int largest (const int x[ ], int size) { // Assume for a moment that the largest // value is stored in x[0] int max = x[0]; for (int i=1; i<size; i++) if (max < x[i]) max = x[i]; return max; }
Example 4 (Cont.) void main() { int array[10] = {4,1,6,3,-5,2,9,5,7,8}; cout << “The largest stored value is “ << largest (array,10) << endl; }
Exercise #1 • Write a function to search for the smallest value stored in a ID array. Your function signature should be like this int smallest (const int x[ ], int size); // purpose – find the smallest value // input – an array x and its size // output – the smallest value Write a C++ program to test your function
Example 5: Searching for The Index of the Largest Value in 1D Array #include <iomanip> #include <string> #include <iostream> using namespace std; int indexOfMaxValue(const int x[ ], int size) { // Assume for a moment that the largest value is stored in x[0] int max = x[0]; int index = 0; for (int i=1; i<size; i++) if (max < x[i]) { max = x[i]; index = i; } return index; }
Exercise#2 • Write a function to search for the index of the smallest value stored in 1D array. Your function signature should be like this Int indexOfMinValue (const int x [ ], int size); // purpose – get the index of the smallest value stored in the array x // input – the array x and its size // output – the index of the smallest value Write a C++ program to test your function
Example 6: Insertion Sort void insertionSort(int x [], int n) { for(int i=0; i<n; i++) swap(x[indexOfMaxValue(x,n-i)], x[n-i-1]); } void printArray(string p, int x[ ], int size) { cout << p; for (int i=0; i<size; i++) cout << setw(3) << x[i]; cout << endl; } Get the index of the largest value stored in the range of [0,n-i] and swap this value in that index with x[n-i-1]
Example 6 (Cont.) void main() { int array[10] = {4,1,3,2,7,6,10,9,5,8}; printArray("Unsorted array:",array, 10); insertionSort(array, 10); printArray("Sorted array: ",array, 10); }
Array ManipulationII. Compute… • The sum of the values stored in an array • The mean and the standard deviation for the array values • The range of the values stored in an array • Multiplying array values by a constant • Dot-product of two arrays • The intersection of two arrays (acting as sets) • The union of two arrays (acting as sets) • The difference between two arrays acting as sets • Binary representation for a given integer number • Generate Fibonacci series • Generate geometric series
Array Manipulation III. Rearranging values of an array • Sorting an array (in ascending or descending order) using bubble sort • Remove duplicate values from an array • Reversing the content of an array