COMP 2710 Software Construction CallbyValue vs CallByReference Arrays
COMP 2710 Software Construction Call-by-Value vs. Call-By-Reference Arrays Dr. Xiao Qin Auburn University http: //www. eng. auburn. edu/~xqin@auburn. edu
Whiteboard Vs. Power. Point 2
Which source code is using call by value and which one is using call by reference? #include <iostream> using namespace std; void change. Value(int &value); void change. Value(int value); int main() { int v = 10; change. Value(v); cout << "v is : " << v << endl; return 0; } } void change. Value(int &value) { value = 20; } void change. Value(int value) { value = 20; } 3
What happens to “call by value”? #include <iostream> using namespace std; void change. Value(int value); int main() { int v = 10; change. Value(v); cout << "v is : " << v << endl; return 0; } v: 10 Memory for main() Memory for change. Value() vaule: 20 void change. Value(int value) { value = 20; } 4
What happens to “call by reference”? #include <iostream> using namespace std; void change. Value(int& value); int main() { int v = 10; change. Value(v); cout << "v is : " << v << endl; return 0; } v: 10 20 Memory for main() Memory for change. Value() vaule: void change. Value(int& value) { value = 20; } 5
Call-by-Value Pitfall • Common Mistake: Declaring parameter "again" inside function double fee(int hours. Worked, int minutes. Worked) { int quarter. Hours; // local variable int minutes. Worked // NO! Why? } – Compiler error results "Redefinition error…” • Value arguments ARE like "local variables" – But function gets them "automatically"
Exercise 1. Call-By-Reference What’s really passed in? int main() { int v = 10; change. Value(v); cout << "v is : " << v << endl; e. g. , what’s passed from main() into change. Value()? return 0; } • A "reference" back to caller’s actual argument. • Refers to memory void change. Value(int &value) location { of actual argument value = 20; } • Called "address", which is a unique number referring to distinct place in memory 4 -7
Arrays – Three Questions 1. How can we pass an array as an input parameter of a function? 2. How can we apply “call by reference” to arrays? Should we still use &? 3. Does the following function prototype work? void change_array(int& array[], int size);
Arrays • Array definition: – A collection of data of same type • First "aggregate" data type – Means "grouping" – int, float, double, char are simple data types • Used for lists of like items – Test scores, temperatures, names, etc. – Avoids declaring multiple simple variables – Can manipulate "list" as one entity 9
Declaring Arrays • Declare the array allocates memory /*Declares array of 5 integers named score*/ int score[5]; • Similar to declaring five variables: int score[0], score[1], score[2], score[3], score[4] 5 -10
Accessing Arrays • Access using index/subscript cout << score[3]; • Size, subscript need not be literal int score[MAX_SCORES]; score[2] = 99; 5 -11
Array Usage • Powerful storage mechanism • Can issue command like: – "Do this to ith indexed variable" where i is computed by program – "Display all elements of array score" – "Fill elements of array score from user input" – "Find highest value in array score" – "Find lowest value in array score" 5 -12
int i, score[5], max; Exercise 2. Can you find an error in this code? What does the main function print out? Suppose we enter: 5 9 2 10 6 cout << "Enter 5 scores: n"; cin >> score[0]; max = score[0]; for (i = 1; i < 10; i++) { cin >> score[i]; if (score[i] > max) max = score[i]; } cout << "The highest score is " << max << endl << "The scores and theirn" << "differences from the highest are: n"; for (i = 0; i < 5; i++) cout << score[i] << " off by " << (max - score[i]) << endl; 5 -13
for-loops with Arrays • Natural counting loop: "counting through" elements of an array • Example: for (idx = 0; idx<5; idx++) { cout << score[idx] << "off by " << max – score[idx] << endl; } 5 -14
Exercise 3. What is wrong with this code? double temperature[24]; /*24 is array size*/ cout << “Enter a temperature: n"; cin >> temperature[24]; Index 24 is "out of range"! No warning, possibly disastrous results What is the last item of the array? 5 -15
Exercise 4. Why we should define array sizes as constants? You may list two reasons. Example: const int NUMBER_OF_STUDENTS = 5; int score[NUMBER_OF_STUDENTS]; for (idx = 0; idx < NUMBER_OF_STUDENTS; idx++) { // Manipulate array • Improves readability } • Improves versatility • Improves maintainability 5 -16
An Array in Memory 5 -17
Initializing Arrays int children[3] = {2, 1}; /* Allocates array b to size 3 */ int b[] = {5, 12, 11}; /* * Fills from beginning. Fills "rest" with * zero of array base type */ int children[5] = {2, 1}; 5 -18
Indexed Variables as Arguments void my. Function(double par 1); int i; double n, a[10]; /* Can make these function calls */ my. Function(i); // i is converted to double my. Function(a[3]); // a[3] is double my. Function(n); // n is double my. Function(a[i*5]); //Is it legal? 5 -19
Entire Arrays as Arguments int score[5], number. Of. Scores = 5; fillup(score, number. Of. Scores); What do you observe here? 5 -20
Exercise 5. What’s really passed to fillup(), when we pass an array as an argument? int score[5], number. Of. Scores = 5; fillup(score, number. Of. Scores); • Think of array as 3 "pieces" – Address of first indexed variable (score[0]) – Array base type – Size of array Address of first indexed variable 5 -21
Exercise 6. Please pass score[] and time[] as array arguments to fillup() int score[30], time[MAX_TIME]; fill. Up(score, 30); fill. Up(time, MAX_TIME); 5 -22
int main() { int nums[9] = {1, 3, 5, 7, 9}; display_array(nums, 5); mys(nums, 5); display_array(nums, 5); return 0; } void mys(int array[], int len) { for (int i = 0; i < len; i++) array[i]++; } Exercise 6. (1) What does this code do? (2) Does mys() use call by reference? 1 3 5 7 9 2 4 6 8 10 Yes, it is call by reference without using & void display_array(int array[], int len) { for (int i = 0; i < len; i++) cout << array[i] << “ “; cout << endl; } 5 -23
The const Parameter Modifier 5 -24
Programming with Arrays • Partially-filled arrays – Must be declared some "max size" • Sorting • Searching 5 -25
Summary • What is Call-by-reference? • Array is collection of "same type" data • for-loop "natural" way to traverse arrays • Programmer responsible for staying "in bounds" of array • Array parameter is "new" kind: Similar to call-by-reference • Array elements stored sequentially: "Contiguous" portion of memory 5 -26
Partially-filled Arrays • Difficult to know exact array size needed • Must declare to be largest possible size – Must then keep "track" of valid data in array – Additional "tracking" variable needed • int number. Used; • Tracks current number of elements in array 5 -27
Partially-filled Arrays Example: Display 5. 5 Partially Filled Array (1 of 5) Copyright © 2012 Pearson Addison-Wesley. All rights reserved. 5 -28
Partially-filled Arrays Example: Display 5. 5 Partially Filled Array (2 of 5) Copyright © 2012 Pearson Addison-Wesley. All rights reserved. 5 -29
Partially-filled Arrays Example: Display 5. 5 Partially Filled Array (3 of 5) Copyright © 2012 Pearson Addison-Wesley. All rights reserved. 5 -30
Partially-filled Arrays Example: Display 5. 5 Partially Filled Array (4 of 5) Copyright © 2012 Pearson Addison-Wesley. All rights reserved. 5 -31
Partially-filled Arrays Example: Display 5. 5 Partially Filled Array (5 of 5) Copyright © 2012 Pearson Addison-Wesley. All rights reserved. 5 -32
Global Constants vs. Parameters • Constants typically made "global" – Declared above main() • Functions then have scope to array size constant – No need to send as parameter then? • Technically yes – Why should we anyway? • Function definition might be in separate file • Function might be used by other programs! Copyright © 2012 Pearson Addison-Wesley. All rights reserved. 5 -33
Searching an Array • Very typical use of arrays • Display 5. 6 next slide Copyright © 2012 Pearson Addison-Wesley. All rights reserved. 5 -34
Display 5. 6 Searching an Array (1 of 4) Copyright © 2012 Pearson Addison-Wesley. All rights reserved. 5 -35
Display 5. 6 Searching an Array (2 of 4) Copyright © 2012 Pearson Addison-Wesley. All rights reserved. 5 -36
Display 5. 6 Searching an Array (3 of 4) Copyright © 2012 Pearson Addison-Wesley. All rights reserved. 5 -37
Display 5. 6 Searching an Array (4 of 4) Copyright © 2012 Pearson Addison-Wesley. All rights reserved. 5 -38
Sorting an Array: Display 5. 7 Selection Short • Selection Sort Algorithm Copyright © 2012 Pearson Addison-Wesley. All rights reserved. 5 -39
Sorting an Array Example: Display 5. 8 Sorting an Array (1 of 4) Copyright © 2012 Pearson Addison-Wesley. All rights reserved. 5 -40
Sorting an Array Example: Display 5. 8 Sorting an Array (2 of 4) Copyright © 2012 Pearson Addison-Wesley. All rights reserved. 5 -41
Sorting an Array Example: Display 5. 8 Sorting an Array (3 of 4) Copyright © 2012 Pearson Addison-Wesley. All rights reserved. 5 -42
Sorting an Array Example: Display 5. 8 Sorting an Array (4 of 4) Copyright © 2012 Pearson Addison-Wesley. All rights reserved. 5 -43
Multidimensional Arrays • Arrays with more than one index – char page[30][100]; • Two indexes: An "array of arrays" • Visualize as: page[0][0], page[0][1], …, page[0][99] page[1][0], page[1][1], …, page[1][99] … page[29][0], page[29][1], …, page[29][99] • C++ allows any number of indexes – Typically no more than two Copyright © 2012 Pearson Addison-Wesley. All rights reserved. 5 -44
Multidimensional Array Parameters • Similar to one-dimensional array – 1 st dimension size not given – • Provided as second parameter 2 nd dimension size IS given • Example: void Display. Page(const char p[][100], int size. Dimension 1) { for (int index 1=0; index 1<size. Dimension 1; index 1++) { for (int index 2=0; index 2 < 100; index 2++) cout << p[index 1][index 2]; cout << endl; } } Copyright © 2012 Pearson Addison-Wesley. All rights reserved. 5 -45
- Slides: 45