Presentation is loading. Please wait.

Presentation is loading. Please wait.

C++ Arrays. Agenda What is an array? What is an array? Declaring C++ arrays Declaring C++ arrays Initializing one-dimensional arrays Initializing one-dimensional.

Similar presentations


Presentation on theme: "C++ Arrays. Agenda What is an array? What is an array? Declaring C++ arrays Declaring C++ arrays Initializing one-dimensional arrays Initializing one-dimensional."— Presentation transcript:

1 C++ Arrays

2 Agenda What is an array? What is an array? Declaring C++ arrays Declaring C++ arrays Initializing one-dimensional arrays Initializing one-dimensional arrays Reading and Writing one-dimensional arrays Reading and Writing one-dimensional arrays Passing one-dimensional arrays to functions Passing one-dimensional arrays to functions Manipulating one-dimensional arrays: Manipulating one-dimensional arrays: Searching for something Searching for something Rearranging stored values Rearranging stored values Computing and storing series of values Computing and storing series of values

3 What Is An Array? An array is a collection of values that have the same data type, e.g. 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 int data values or A collection of bool data values A collection of bool data values We refer to all stored values in an array by its name 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) 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 first array index is always 0 The second value is stored in index 1 The second value is stored in index 1 Etc. Etc.

4 How To Declare Arrays To declare an array in C++, you should specify the following things 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 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 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: The dimensionality of the array: One dimensional (i.e. list of values ), One dimensional (i.e. list of values ), Two-dimension array (a matrix or a table), etc. Two-dimension array (a matrix or a table), etc. The size of each dimension The size of each dimension Examples Examples int x[10]; // An integer array named x with size 10 int x[10]; // An integer array named x with size 10 float GPA[30]; // An array to store the GPA for 30 students 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 int studentScores[30][5]; // A two-dimensional array to store the scores of 5 exams for 30 students

5 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. 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 1 st value is 10 x[0] = 10; // the 1 st value is 10 x[1] = 5; // the 2 nd value is 5 x[1] = 5; // the 2 nd value is 5 x[2] = 20; // the 3 rd value is 20 x[2] = 20; // the 3 rd value is 20 x[3] = 30; // the 4 th value is 30 x[3] = 30; // the 4 th value is 30 10 5 20 30 x[0] x[1] x[2] x[3]

6 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 All C++ one-dimensional arrays with N entries start at index 0 and ended at index N-1 const int N=5; const int N=5; int v[N]; // this array contains 5 entries int v[N]; // this array contains 5 entries It is a common error to try to access the N th entry, e.g. v[5] or V[N], since the index of the last array entry is N-1, not N It is a common error to try to access the N th entry, e.g. v[5] or V[N], since the index of the last array entry is N-1, not N

7 Initializing One-dimensional Arrays There are two common ways to initialize one-dimensional arrays There are two common ways to initialize one-dimensional arrays Using for loop, e.g. Using for loop, e.g. int x[10]; int x[10]; for( int index=0; index<10; index++) x [index] = index+1 ; for( int index=0; index<10; index++) x [index] = index+1 ; Specifying list of values while declaring the 1D array, e.g. 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 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 int y[ ] = {0,0,0}; // this array contains 3 entries with 0 values double z[100] = {0}; // this array contains 100 double z[100] = {0}; // this array contains 100 // entries, all of which are initialized by 0 // entries, all of which are initialized by 0 double w[20] = {5,3,1}; // this array contains 20 entries, double w[20] = {5,3,1}; // this array contains 20 entries, // the first three entries are initialized by 5, 3, and1 respectively // the first three entries are initialized by 5, 3, and1 respectively // while the remaining 17 entries are automatically initialized by 0 // while the remaining 17 entries are automatically initialized by 0 bool pass[10] = {true, true}; // this array contains 10 entries. bool pass[10] = {true, true}; // this array contains 10 entries. // The first two entries are initialized to true, while the remaining 8 // The first two entries are initialized to true, while the remaining 8 // entries are automatically initialized to false // entries are automatically initialized to false

8 Storing Values in 1D Arrays Wrong way: Wrong way: Int x[10]; cin >> x ; // you cannot do that unless you // overload the >> operator! // overload the >> operator! // Wait until you take CSCI-110 // Wait until you take CSCI-110 Correct way: Correct way: int x[10]; int x[10]; // Reading one value at a time from the user: // Reading one value at a time from the user: for (int index=0; index<10; index++) for (int index=0; index<10; index++) cin >> x[index]; cin >> x[index];

9 Displaying Values Stored in 1D Arrays Wrong way: Wrong way: Int x[10]; cout << x; // you cannot do that unless you // overload the << operator! // overload the << operator! // Wait until you take CSCI-110 // Wait until you take CSCI-110 Correct way: Correct way: int x[10]; int x[10]; // Displaying one value per line to the user: // Displaying one value per line to the user: for (int index=0; index<10; index++) for (int index=0; index<10; index++) cout << x[index] << endl; cout << x[index] << endl;

10 Example: Read Values and Print them in Reverse Order #include #include void main() { int x[5], index; int x[5], index; cout << “Please enter five integer values: “; cout << “Please enter five integer values: “; for( index=0; index > x[index]; for( index=0; index > x[index]; cout << “The values in reverse order are: “; cout << “The values in reverse order are: “; for (index=4; index>=0; index--) for (index=4; index>=0; index--) cout << setw(3) << x[index]; cout << setw(3) << x[index]; cout << endl; cout << endl;}

11 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? 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 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 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) 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);

12 Passing 1D Arrays to Functions Why don’t we use the following signature to pass an array to a function? 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!) 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 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! 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!

13 Example 2: Passing 1D Array to A Function #include #include using namespace std; void display (string prompt, int x[ ], int n) { cout << prompt ; cout << prompt ; for (int i=0; i<n; i++) for (int i=0; i<n; i++) cout << setw(3) << x[i]; cout << setw(3) << x[i]; cout << endl; cout << endl;} void main() { int v[7] = {1,2,3,4}; int v[7] = {1,2,3,4}; int w[4] = {10,20,30,40}; int w[4] = {10,20,30,40}; display ("The values of v array : ", v, 7); display ("The values of v array : ", v, 7); display ("The values of w array : ", w, 4); display ("The values of w array : ", w, 4);}

14 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. 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++) for (int i=0; i<size; i++) cout << x[i] << endl; cout << x[i] << endl;}

15 Array Manipulation I. Searching for Something…

16 Example: Searching for the smallest value in an array int smallest (const int x[ ], int n) { /* Assume for a moment that x[0] contains /* Assume for a moment that x[0] contains the smallest value */ the smallest value */ int min = x[0]; int min = x[0]; for (int i=1; i x[i]) min = x[i]; for (int i=1; i x[i]) min = x[i]; return min; return min;}

17 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 index = start; int min = x[index]; int min = x[index]; for (int i=index+1; i<size; i++) for (int i=index+1; i<size; i++) if (min>x[i]) if (min>x[i]) { min = x[i]; min = x[i]; index = i; index = i; } return index; return index;} Notice that: 1.The array is not sorted! 2.We use the parameter start to specify the start searching index. The 0 is the default value of this parameter 3.Later on, we will use this function to sort an array

18 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++) for (int i=0; i<size; i++) if (key == x[i]) return i; if (key == x[i]) return i; return -1; return -1;} This function will return the index of the first value that equals to the key if exists, otherwise, it returns -1

19 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; int left=0, right=n-1; do do { int mid = (left+right)/2; int mid = (left+right)/2; if (x[mid] == key) return mid; if (x[mid] == key) return mid; if (x[mid]<key) if (x[mid]<key) right=mid-1; right=mid-1; else else left=mid+1; left=mid+1; } while (left<=right); } while (left<=right); return -1; return -1;} NB. 1.The array x must be sorted! 2.Each loop iteration eliminate half of the current length of the array which makes this searching technique more faster than the sequential search 3.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

20 Array Manipulation II. Compute Something…

21 Example: Compute The Sum of Values Stored in An Array int sum (const int x[ ], int n) { int s = 0; int s = 0; for (int i=0; i<n; i++) s+=x[i]; for (int i=0; i<n; i++) s+=x[i]; return s; return s;}

22 Example: Compute The Mean Value of An Array double mean (const int x[ ], int n) { return (double) sum(x,n) / n; return (double) sum(x,n) / n;}

23 Example: Compute The Standard Deviation of An Array double stdiv (const int x[ ], int x) { double ss = 0.0, xBar = mean(x,n); double ss = 0.0, xBar = mean(x,n); for(int i=1; i<n; i++) ss+=pow(x[i]-xBar,2); for(int i=1; i<n; i++) ss+=pow(x[i]-xBar,2); if (n<30) if (n<30) return sqrt(ss/(n-1)); return sqrt(ss/(n-1)); else else return sqrt(ss/n); return sqrt(ss/n);}

24 Example: Compute The Range of Numbers int range (const int x[ ], int n) { return max (x, n) – min (x, n); return max (x, n) – min (x, n);}

25 Example: Compute The Median double median( double x[], int n) { sort (x, n); //assume sort( ) is already defined sort (x, n); //assume sort( ) is already defined if (n % 2 == 1) if (n % 2 == 1) return x[n/2+1]; return x[n/2+1]; else else return (x[n/2]+x[n/2+1)/2; return (x[n/2]+x[n/2+1)/2;}

26 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; for (int i=0; i<n; i++) x[i] *= value;}

27 Example: Dot Product of Two Arrays int dotProduct( int x[ ], int y[ ], int n) { int sum = 0; int sum = 0; for (int i=0; i<n; i++) for (int i=0; i<n; i++) sum += x[i] * y[i]; sum += x[i] * y[i]; return sum; return sum;}

28 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]; 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]; for (int i=0; i<n; i++) z[i] = x[i] - y[i];}

29 Example: Set Intersection void intersection (const int set1[], int size1, const int set2[], int size2, int s[], int &size) { size=0; size=0; for(int i=0; i<size1; i++) for(int i=0; i<size1; i++) if (seqSearch(set2, size2, set1[i])>-1) if (seqSearch(set2, size2, set1[i])>-1) set[size++] = set1[i]; set[size++] = set1[i];}

30 Example: Set Difference void difference (const int set1[], int size1, const int set2[], int size2, int s[], int &size) { size=0; size=0; for(int i=0; i<size1; i++) for(int i=0; i<size1; i++) if (seqSearch(set2, size2, set1[i]) == -1) if (seqSearch(set2, size2, set1[i]) == -1) set[size++] = set1[i]; set[size++] = set1[i];}

31 Example: Set Union void union (const int set1[], int size1, const int set2[], int size2, int s[], int &size) { size = size1; size = size1; for(int i=0; i<size; i++) set[i]=set1[i]; for(int i=0; i<size; i++) set[i]=set1[i]; for(int i=0; i<size2; i++) for(int i=0; i<size2; i++) if (seqSearch(set, size, set2[i]) == -1) if (seqSearch(set, size, set2[i]) == -1) set[size++] = set2[i]; set[size++] = set2[i];}

32 Example: Converting An Integer Decimal Number to Binary Number #include #include void main() { short int binary[64]={0}; short int binary[64]={0}; int index, bits=0; int index, bits=0; unsigned int n; unsigned int n; cout << "Please enter an integer value: "; cout << "Please enter an integer value: "; cin >> n; cin >> n; cout << "The binary number is "; cout << "The binary number is "; if (n==0) if (n==0) cout << 0 << endl; cout << 0 << endl; else else { while (n>0) while (n>0) { binary[bits] = n % 2; binary[bits] = n % 2; n /= 2; n /= 2; bits++; bits++; } for (index=bits-1;index>=0;index--) for (index=bits-1;index>=0;index--) cout << binary[index]; cout << binary[index]; cout << endl; cout << endl; }} Guess what happens when you enter -1!

33 Example #2: Converting an integer decimal number to binary number #include #include void main() { short int binary[64]={0}; short int binary[64]={0}; int index, bits=0; int index, bits=0; unsigned int n; unsigned int n; cout << "Please enter an integer value: "; cout << "Please enter an integer value: "; cin >> n; cin >> n; cout << "The binary number is "; cout << "The binary number is "; if (n==0) if (n==0) cout << 0 << endl; cout << 0 << endl; else else { while (n>0) while (n>0) { binary[bits] = n % 2; binary[bits] = n % 2; n /= 2; n /= 2; bits++; bits++; } for (index=bits-1;index>=0;index--) for (index=bits-1;index>=0;index--) cout << binary[index]; cout << binary[index]; cout << endl; cout << endl; }} Guess what happens when you enter -1!

34 Example 4: Search for The Largest Value in 1D Array #include #include int largest (const int x[ ], int size) { // Assume for a moment that the largest // Assume for a moment that the largest // value is stored in x[0] // value is stored in x[0] int max = x[0]; int max = x[0]; for (int i=1; i<size; i++) if (max < x[i]) max = x[i]; for (int i=1; i<size; i++) if (max < x[i]) max = x[i]; return max; return max;}

35 Example 4 (Cont.) void main() { int array[10] = {4,1,6,3,-5,2,9,5,7,8}; int array[10] = {4,1,6,3,-5,2,9,5,7,8}; cout << “The largest stored value is “ cout << “The largest stored value is “ << largest (array,10) << largest (array,10) << endl; << endl;}

36 Exercise #1 Write a function to search for the smallest value stored in a ID array. Your function signature should be like this 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

37 Example 5: Searching for The Index of the Largest Value in 1D Array #include #include using namespace std; int indexOfMaxValue(const int x[ ], int size) { // Assume for a moment that the largest value is stored in x[0] // Assume for a moment that the largest value is stored in x[0] int max = x[0]; int max = x[0]; int index = 0; int index = 0; for (int i=1; i<size; i++) for (int i=1; i<size; i++) if (max < x[i]) if (max < x[i]) { max = x[i]; max = x[i]; index = i; index = i; } return index; return index;}

38 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 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

39 Example 6: Insertion Sort void insertionSort(int x [], int n) { for(int i=0; i<n; i++) for(int i=0; i<n; i++) swap(x[indexOfMaxValue(x,n-i)], x[n-i-1]); swap(x[indexOfMaxValue(x,n-i)], x[n-i-1]);} void printArray(string p, int x[ ], int size) { cout << p; cout << p; for (int i=0; i<size; i++) cout << setw(3) << x[i]; for (int i=0; i<size; i++) cout << setw(3) << x[i]; cout << endl; 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]

40 Example 6 (Cont.) void main() { int array[10] = {4,1,3,2,7,6,10,9,5,8}; int array[10] = {4,1,3,2,7,6,10,9,5,8}; printArray("Unsorted array:",array, 10); printArray("Unsorted array:",array, 10); insertionSort(array, 10); insertionSort(array, 10); printArray("Sorted array: ",array, 10); printArray("Sorted array: ",array, 10);}

41 Array Manipulation II. Compute… The sum of the values stored in an array The sum of the values stored in an array The mean and the standard deviation for the array values The mean and the standard deviation for the array values The range of the values stored in an array The range of the values stored in an array Multiplying array values by a constant Multiplying array values by a constant Dot-product of two arrays Dot-product of two arrays The intersection of two arrays (acting as sets) The intersection of two arrays (acting as sets) The union of two arrays (acting as sets) The union of two arrays (acting as sets) The difference between two arrays acting as sets The difference between two arrays acting as sets Binary representation for a given integer number Binary representation for a given integer number Generate Fibonacci series Generate Fibonacci series Generate geometric series Generate geometric series

42 Array Manipulation III. Rearranging values of an array Sorting an array (in ascending or descending order) using bubble sort Sorting an array (in ascending or descending order) using bubble sort Remove duplicate values from an array Remove duplicate values from an array Reversing the content of an array Reversing the content of an array


Download ppt "C++ Arrays. Agenda What is an array? What is an array? Declaring C++ arrays Declaring C++ arrays Initializing one-dimensional arrays Initializing one-dimensional."

Similar presentations


Ads by Google