42
C++ Arrays C++ Arrays

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

Embed Size (px)

Citation preview

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

C++ ArraysC++ Arrays

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

AgendaAgenda

What is an array?What is an array? Declaring C++ arraysDeclaring C++ arrays Initializing one-dimensional arraysInitializing one-dimensional arrays Reading and Writing one-dimensional arraysReading and Writing one-dimensional arrays Passing one-dimensional arrays to functionsPassing one-dimensional arrays to functions Manipulating one-dimensional arrays:Manipulating one-dimensional arrays:

Searching for something Searching for something Rearranging stored valuesRearranging stored values Computing and storing series of valuesComputing and storing series of values

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

What Is An Array?What Is An Array? An array is a collection of values that have the An array is a collection of values that have the

same data type, e.g. same data type, e.g. A collection of int data values or A collection of int data values or A collection of bool data valuesA collection of bool data values

We refer to all stored values in an array by its We refer to all stored values in an array by its namename

If we would like to access a particular value If we would like to access a particular value stored in an array, we specify its index (i.e. its stored in an array, we specify its index (i.e. its position relative to the first array value)position relative to the first array value) The first array index is always 0The first array index is always 0 The second value is stored in index 1The second value is stored in index 1 Etc.Etc.

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

How To Declare ArraysHow To Declare Arrays To declare an array in C++, you should specify the To declare an array in C++, you should specify the

following thingsfollowing things The data type of the values which will be stored in the arrayThe 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 The name of the array (i.e. a C++ identifier that will be used to

access and update the array values)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 dimensionThe size of each dimension ExamplesExamples

int x[10];int x[10]; // An integer array named x with size 10 // An integer array named x with size 10 float GPA[30];float GPA[30]; // An array to store the GPA for 30 students // An array to store the GPA for 30 students int studentScores[30][5];int studentScores[30][5]; // A two-dimensional array to store the // A two-dimensional array to store the

scores of 5 exams for 30 studentsscores of 5 exams for 30 students

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

One-dimensional ArraysOne-dimensional Arrays

We use one-dimensional (ID) arrays to store and We use one-dimensional (ID) arrays to store and access list of data values in an easy way by access list of data values in an easy way by giving these values a common name, e.g.giving these values a common name, e.g.

int x[4];int x[4]; // all values are named x // all values are named x

x[0] = 10;x[0] = 10; // the 1 // the 1stst value is 10 value is 10

x[1] = 5;x[1] = 5; // the 2 // the 2ndnd value is 5 value is 5

x[2] = 20;x[2] = 20; // the 3 // the 3rdrd value is 20 value is 20

x[3] = 30;x[3] = 30; // the 4 // the 4thth value is 30 value is 30

10

5

20

30

x[0]

x[1]

x[2]

x[3]

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

Array Indices and Array Indices and Out-of-bound Run-time ErrorOut-of-bound Run-time Error

All C++ one-dimensional arrays with N All C++ one-dimensional arrays with N entries start at index 0 and ended at index entries start at index 0 and ended at index N-1N-1

const int N=5;const int N=5;

int v[N]; // this array contains 5 entriesint v[N]; // this array contains 5 entries It is a common error to try to access the It is a common error to try to access the

NNthth entry, e.g. v[5] or V[N], since the index entry, e.g. v[5] or V[N], since the index of the last array entry is N-1, not Nof the last array entry is N-1, not N

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

Initializing One-dimensional ArraysInitializing One-dimensional Arrays

There are two common ways to initialize one-dimensional arraysThere 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};int y[ ] = {0,0,0}; // this array contains 3 entries with 0 values // this array contains 3 entries with 0 values double z[100] = {0};double z[100] = {0}; // this array contains 100 // 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};double w[20] = {5,3,1}; // this array contains 20 entries, // 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};bool pass[10] = {true, true}; // this array contains 10 entries. // 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

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

Storing Values in 1D ArraysStoring Values in 1D Arrays Wrong way:Wrong way:

Int x[10];Int x[10];cin >> xcin >> x; ; // you cannot do that unless you // 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];

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

Displaying Values Stored Displaying Values Stored in 1D Arraysin 1D Arrays

Wrong way:Wrong way:Int x[10];Int x[10];cout << x;cout << x; // you cannot do that unless you // 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;

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

Example: Read Values and Print Example: Read Values and Print them in Reverse Orderthem in Reverse Order

#include <iomanip.h>#include <iomanip.h>void main()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<5; index++) cin >> x[index];for( index=0; index<5; index++) cin >> 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;}}

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

Passing 1D Arrays to FunctionsPassing 1D Arrays to Functions By default, arrays are passed to functions by By default, arrays are passed to functions by

reference even though we do not even write the reference even though we do not even write the reference operator (&) in front of the array name, reference operator (&) in front of the array name, why?why? Since arrays store huge number of values, it is much Since arrays store huge number of values, it is much

faster and more economical to pass arrays by faster and more economical to pass arrays by reference instead of wasting the time and memory reference instead of wasting the time and memory copying the values of the arrays into another arrayscopying the values of the arrays into another arrays

ExampleExample The following function signature accepts an array x as The following function signature accepts an array x as

a reference parameter and it also accepts the number a reference parameter and it also accepts the number of entries in the array (i.e. its size)of entries in the array (i.e. its size)

void process (int x[], int size);void process (int x[], int size);

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

Passing 1D Arrays to FunctionsPassing 1D Arrays to Functions Why don’t we use the following signature to pass an Why don’t we use the following signature to pass an

array to a function?array to a function?void process (int x[10]);void process (int x[10]);

Unfortunately, using the above signature means that this Unfortunately, using the above signature means that this particular function will only process a 1D array with size particular function will only process a 1D array with size =10 (no more no less!)=10 (no more no less!)

Of course we would like to write a function to handle Of course we would like to write a function to handle different array sizes and that is why we use the following different array sizes and that is why we use the following signature insteadsignature instead

void process (int x[ ], int size);void process (int x[ ], int size); Visual Studio in particular does not issue any warnings Visual Studio in particular does not issue any warnings

or syntax error if you use the first signature and pass or syntax error if you use the first signature and pass different array size, but other compliers do!different array size, but other compliers do!

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

Example 2: Passing 1D Array to A Example 2: Passing 1D Array to A Function Function

#include <iomanip>#include <iomanip>#include <iostream>#include <iostream>#include <string>#include <string>using namespace std;using namespace std;

void display (string prompt, void display (string prompt, int x[ ], int n)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()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 : ", display ("The values of v array : ",

v, 7);v, 7); display ("The values of w array : ", display ("The values of w array : ",

w, 4);w, 4);}}

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

Passing 1D Arrays As const Passing 1D Arrays As const Reference ParametersReference Parameters

It is a good idea to pass arrays as const It is a good idea to pass arrays as const reference parameters if you want to reference parameters if you want to assure that the functions will never change assure that the functions will never change the values stored in the arrays, e.g.the values stored in the arrays, e.g.

void display (const int x[ ] , int size)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;}}

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

Array ManipulationArray Manipulation

I. Searching for Something…I. Searching for Something…

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

Example: Searching for the Example: Searching for the smallest value in an arraysmallest value in an array

int smallest (const int x[ ], int n)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<n; i++) if (min>x[i]) min = x[i];for (int i=1; i<n; i++) if (min>x[i]) min = x[i]; return min;return min;}}

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

Example: Searching for The Index Example: Searching for The Index of The Smallest Value in An Arrayof The Smallest Value in An Array

int min_index (int x[ ], int size, int start=0)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

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

Example: Searching for A Key in Example: Searching for A Key in Unsorted Array Using Sequential SearchUnsorted Array Using Sequential Search

int seqSearch (int x[ ], int size, int key)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

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

Example: Searching for A Key in A Example: Searching for A Key in A Sorted Array Using Binary SearchSorted Array Using Binary Search

int bSearch (int x[ ],int n,int key)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; elseelse 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

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

Array ManipulationArray Manipulation

II. Compute Something…II. Compute Something…

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

Example: Compute The Sum of Example: Compute The Sum of Values Stored in An ArrayValues Stored in An Array

int sum (const int x[ ], int n)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;}}

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

Example: Compute The Mean Example: Compute The Mean Value of An ArrayValue of An Array

double mean (const int x[ ], int n)double mean (const int x[ ], int n)

{{

return (double) sum(x,n) / n;return (double) sum(x,n) / n;

}}

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

Example: Compute The Standard Example: Compute The Standard Deviation of An ArrayDeviation of An Array

double stdiv (const int x[ ], int x)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)); elseelse return sqrt(ss/n);return sqrt(ss/n);}}

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

Example: Compute The Range of Example: Compute The Range of NumbersNumbers

int range (const int x[ ], int n)int range (const int x[ ], int n)

{{

return max (x, n) – min (x, n);return max (x, n) – min (x, n);

}}

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

Example: Compute The Median Example: Compute The Median

double median( double x[], int n)double median( double x[], int n){{ sort (x, n); //assume sort( ) is already definedsort (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]; elseelse return (x[n/2]+x[n/2+1)/2;return (x[n/2]+x[n/2+1)/2;}}

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

Example: Multiplying An Array with Example: Multiplying An Array with A Constant ValueA Constant Value

void multiply( int x[ ], int n, const int 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;

}}

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

Example: Dot Product of Two Example: Dot Product of Two ArraysArrays

int dotProduct( int x[ ], int y[ ], int n)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;}}

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

Example: Adding/Subtracting Two Example: Adding/Subtracting Two arraysarrays

void add (const int x[], const int y[], int z[], nt n)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)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];}}

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

Example: Set IntersectionExample: Set Intersection

void intersection (const int set1[], int size1,void intersection (const int set1[], int size1,const int set2[], int size2, int s[], int &size)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];}}

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

Example: Set Difference Example: Set Difference

void difference (const int set1[], int size1,void difference (const int set1[], int size1,const int set2[], int size2, int s[], int &size)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];}}

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

Example: Set UnionExample: Set Union

void union (const int set1[], int size1,void union (const int set1[], int size1,const int set2[], int size2, int s[], int &size)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];}}

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

Example: Converting An Integer Example: Converting An Integer Decimal Number to Binary NumberDecimal Number to Binary Number

#include <iomanip.h>#include <iomanip.h>void main()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; elseelse

{{ 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!

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

Example #2: Converting an integer Example #2: Converting an integer decimal number to binary numberdecimal number to binary number

#include <iomanip.h>#include <iomanip.h>void main()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; elseelse

{{ 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!

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

Example 4: Search for The Largest Example 4: Search for The Largest Value in 1D ArrayValue in 1D Array

#include <iostream.h>#include <iostream.h>

int largest (const int x[ ], int size)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;}}

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

Example 4 (Cont.)Example 4 (Cont.)

void main()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;

} }

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

Exercise #1Exercise #1

Write a function to search for the smallest Write a function to search for the smallest value stored in a ID array. Your function value stored in a ID array. Your function signature should be like thissignature should be like this

int smallest (const int x[ ], int size);int smallest (const int x[ ], int size);

// purpose – find the smallest value// purpose – find the smallest value

// input – an array x and its size// input – an array x and its size

// output – the smallest value// output – the smallest value

Write a C++ program to test your function Write a C++ program to test your function

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

Example 5: Searching for The Index of Example 5: Searching for The Index of the Largest Value in 1D Arraythe Largest Value in 1D Array

#include <iomanip>#include <iomanip>#include <string>#include <string>#include <iostream>#include <iostream>using namespace std;using namespace std;

int indexOfMaxValue(const int x[ ], int size)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;}}

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

Exercise#2Exercise#2

Write a function to search for the index of the Write a function to search for the index of the smallest value stored in 1D array. Your function smallest value stored in 1D array. Your function signature should be like thissignature should be like this

Int indexOfMinValue (const int x [ ], int size);Int indexOfMinValue (const int x [ ], int size);// purpose – get the index of the smallest value stored in // purpose – get the index of the smallest value stored in

the array xthe array x// input – the array x and its size// input – the array x and its size// output – the index of the smallest value// output – the index of the smallest value

Write a C++ program to test your functionWrite a C++ program to test your function

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

Example 6: Insertion SortExample 6: Insertion Sort

void insertionSort(int x [], int n)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)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]

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

Example 6 (Cont.)Example 6 (Cont.)void main()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);

}}

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

Array ManipulationArray ManipulationII. Compute…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 The mean and the standard deviation for the array

valuesvalues 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

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

Array ManipulationArray Manipulation III. Rearranging values of an array III. Rearranging values of an array

Sorting an array (in ascending or Sorting an array (in ascending or descending order) using bubble sortdescending order) using bubble sort

Remove duplicate values from an arrayRemove duplicate values from an array

Reversing the content of an arrayReversing the content of an array