Presentation is loading. Please wait.

Presentation is loading. Please wait.

Arrays.

Similar presentations


Presentation on theme: "Arrays."— Presentation transcript:

1 Arrays

2 Arrays Up to now, variables have only held a single value.
Now we introduce a kind of compound variables, that is variables which can hold multiple values. An array is designed to hold homogeneous values. That is, every value in an array is of the same type. For example: int c[10]; // c is an array of 10 integers. double x[22]; // x is an array of 22 doubles char letters[30]; //letters is an array of 30 characters The size, or dimensionality, of the array must be declared so that compiler knows how much storage to set aside.

3 Element Reference We can access individual elements of an array (see previous slide) via an index, like: c[3] = 13; x[20] = x[17] - x[3]; Notice that the "first" element of the array actually has index 0. The implication is that there is no such thing as c[10], x[22] or letters[30]. The indices of an array of size n run from 0 to n-1.

4 Initialization of Arrays
Arrays are initialized using an initialization block int a = 3; int fib[10] = {1, 1, 2, 3, 5, 8, 13, 21, 34, 55}; Note that it is not necessary to initialize every element of an array. int a[10] = {4, -5, 7, -11, 9}; initializes a[0] through a[4] while leaving a[5] through a[9] uninitialized. As you might expect, specifying too many elements (over specifying) is a compile-time error.

5 Array Storage Here is a diagram of how an array get's stored in memory. The elements in an array are stored adjacent to one another. The diagram shows a series of contiguous memory locations, each holding a piece of integer data. Underneath each location we show, in square brackets, the index of the piece of data within the array. Don't confuse the two. The index gives the position within the array. It is always an integer!

6 The data in the boxes represent the value of each element of the array
The data in the boxes represent the value of each element of the array. Their type depends on the type of the array. This is an array of integers, so the values are integers, but we could have an array of doubles or characters just as well. In the figure the element at index 6 is 7, while that at 11 is 17. An array is accessed directly, simply by specifying the index of the desired element (this is actually what is meant by the term random access).

7 Passing Arrays to Functions
An array can be passed into a function as an argument For example, in the function prototype below an array of grades is passed in as input and the function returns the average of the grades. double average(int grades[], int size) Because arrays do not know their own size, the size must be passed in as a separate parameter. Obviously the programmer who originally created the array (outside our function) must know how big the array she created is. But our function has to be able to work with classes of any size. So, as part of our contract, we get clients to tell us how big their array is.

8 We pass arrays by reference.
Actually, they are technically passed by address because arrays are an original feature of C and C didn't have pass-by-reference. The difference at your stage is not worth worrying about. Bottom line: any changes to an array passed to a function is permanent after we return from that function

9 For loops and Arrays For loops and Arrays are like peanut butter and jelly Sandwich int main( ){ const int SIZE_S = 10; const int SIZE_C = 5; double sines[SIZE_S]; double cosines[SIZE_C]; int i; // used to index through both arrays // Fill up the arrays for (i = 0; i < SIZE_S; i++) sines[i] = fabs(sin(2* *i/SIZE_S)); for (i = 0; i < SIZE_C; i++) cosines[i] = fabs(cos(2* *i/SIZE_C)); //call function average below cout << "The average of the sines is " << average(sines, SIZE_S) << endl; cout << "& the average of the cosines is " << average(cosines, SIZE_C) << endl; return 0; }

10 /** average ************************************************ *
* @params: data - the array of data to be averaged * size: the number of elements in the data array * Modifies: nothing the average of the data ***********************************************************/ double average(double data[], int size){ double sum = 0.; for (int i = 0; i < size; i++) sum += data[i]; return sum/size; } //using while loop double average(double data[], int size){ double sum=0.0; int i=0; while (i<size){ sum+=data[i]; i++; } return sum/size

11 Problem: build a function to find the position of the largest piece of data in an array of doubles
Clearly a loop is involved since I'll have to search the entire array—and for loops are a good match for arrays concentrate on the body of the loop, assume I know the position of the largest piece of data so far We'll hold that in a variable called position, so we should get something like search the whole array ( use: for i = 0, i < arraysize) if data[i] > data[position] then position = i Now all we have to do is get it started—how about we set position to 0? In other words, force an assumption that the largest data is initially at position 0

12 /. getLargest. @params: data - an array of doubles
/** getLargest ****************************************** * data - an array of doubles * size: number of elements in the data array * Modifies: nothing the position of the first occurrence of the * largest value ********************************************************/ int getLargest(double data[], int size){ int position = 0; for (int i = 1; i < size; i++) if (data[i] > data[position]) position = i; return position; }

13 What would we change if we wanted the last occurrence?
Question: What happens if there are two or more largest pieces of data? Where will position end up? It returns the first position of the largest data What would we change if we wanted the last occurrence? if (data[i] >= data[position]) position = i;

14 Problem: build a function to find how many occurrences there are of the largest piece of data in an array of doubles. int howManyLargest(double data[], int size){ // first occurrence of largest data - see previous slides int position = getLargest( data, size); int count = 1; //we have one occurrence so far //start searching after the 1st occurrence for( int i=position+1; i<size; i++) { if(data[i]==data[position]) count++; } return count; }

15 Another Solution int howManyLargest(double data[], int size){ int pos=0; int count=1; for (int i=1; i<size; i++){ if(data[i]>data[pos]){ pos=i; count=1; } else if (data[i]==data[pos]) count++; return count;

16 The break statement The keyword break inside a for loop exists the loop immediately Example: find the first occurrence of the number 3 in an integer array, if it is not found then return -1 int findNum3(int data[], int size) { int pos = -1; for (int i = 0; i<size; i++) if (data[i] == 3) { pos = i; break; } return pos; This code is more efficient because it stops once it found the number 3 and does not keep searching until the end of the array

17 Things you cannot do with Arrays
You cannot return an array from a function. Example: double[ ] foo() { double myArray[3]={4.2, 3.1,12.6}; return myArray; } is not legal. Remember that arrays are pass by reference so the changes are permanent

18 Things you cannot do with Arrays
You cannot assign arrays. double A[3]={4.2, 3.1,12.6}; double B[3]; B = A; The third line is not legal. Instead, write a loop for (int i = 0; i < 3; i++) B[i] = A[i];

19 Things you cannot do with Arrays
When declaring arrays, you must know their size at compile time. For example: void foo(int size){ double A[size]; .... } is not legal since arguments to functions are only known at run time, when the function actually gets called. Another way to think of this is that arrays should be declared with constant sizes. Either of these is legal double A[20]; OR const int SIZE = 30; double B[SIZE];

20 Example This question deals with digital audio (e.g., music), which is essentially an array of sound samples, where each sample represents the amplitude of the sound wave at a particular instant. A fuzz box creates a distortion effect common in rock guitar music by 'clipping' the maximum amplitude to the given value, as illustrated. Write the prototype and implementation of the header block shown below.

21 /*** fuzzBox ******************************* * Clip the size samples in snd to a maximum amplitude (magnitude) snd - audio samples array * size - the number of samples in snd * clip - the maximum magnitude in the output Any element in snd that has a magnitude greater than clip * will be set to clip or – clip to preserve the sign The number of samples that had their values changed **/ int fuzzBox(int snd[], int size, int clip) { For loop(traverse all array) Check the current element if it is above the positive threshold clip the value to clip increment the counter Do something similar for the negative threshold return counter } i

22 /*** fuzzBox ******************************* * Clip the size samples in snd to a maximum amplitude (magnitude) snd - audio samples array * size - the number of samples in snd * clip - the maximum magnitude in the output Any element in snd that has a magnitude greater than clip * will be set to clip or – clip to preserve the sign The number of samples that had their values changed **/ int fuzzBox(int snd[], int size, int clip) { int cnt = 0 ; for ( int i=0 ; i < size; i++) { if(snd[i] > clip){ snd [i] = clip; cnt++; } else if (snd[i]<-clip) { snd[i]= -clip; } return cnt;

23 Example Write a function named "number_of_matches" that compares the initial parts of two character arrays to see how many pairs of cells match before a difference occurs. For example, if the arrays are The function should return 3 because only the first three characters in the first array matches the corresponding cells in the second array H E L O - 1 2 H E L I C O P T R Example execusion int main() { char s1[10] = { 'H','E','L', 'L', 'O', '-', '1', '0', '2', '0' }; char s1[10] = { 'H','E','L', 'I', 'C', 'O', 'P', 'T', 'E', 'R' }; cout << number_of_matches(s1,s2,10); return 0; } will print 3 on the screen

24 int number_of_matches (char firstWord[], char secondWord[], int size) { int cnt=0; for ( int i=0 ; i < size; i++) { if(firstWord[i]==secondWord[i]) cnt++; else break; } return cnt; For

25 Time for a break After all this array stuff, let’s meditate Have fun


Download ppt "Arrays."

Similar presentations


Ads by Google