
























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!

























Read: Chpt. 7.
Suppose Prof. LazyCrazy decides: ° There needs to be 104 homework assignments and 57 tests for EECS168. ° From time to time, we may increase or decrease the numbers, so your code needs to be written very generally. ° You need to implement a program to compute the average of homeworks and tests. ° You need to carefully format output reports so that we can have, say, 10 scores per line in regular labeled columns.
Rather than using variables hw1, hw2, hw3, …, of int type, we need a way to define and organize large numbers of objects of the same type.
Solution: Use arrays.
Array : It is an ordered collection of data of the same type organized in such a way that its elements (data) can be accessed through indexing
Some Advantages in using Array:
Array declaration: Syntax: type_name array_name[sizeOfArray];
Base type → type_name Array name → array_name Array size → sizeOfArray
Examples: int homework[104]; char grade[5]; double arrayExample[8]; int numStudents, examScores[3], hwScores[10];
Properties: ° The size of an array is given in square brackets when the array name is first declared. ° Once declared, the size of an array cannot be changed. ° The size of the array must be known at compile time. It can also involve an expression. const int numBeansPerPod = 20; const int maxNumPods = 30; int podHolder[numBeansPerPodmaxNumPods]; ° When we study dynamic memory allocation later, we will see that arrays can be created with a size computed at run time, but even then, once allocated, its size can not be changed. ° Do not confuse the use of brackets at declaration time from their meaning at access time! double weights[20]; // ‘20’ is size of array weights[3] = 1.3; // ‘3’ refers to the 4 th^ element ° Indices may be integer variables/expressions: int which = 7; weights[which] = 1.3; weights[2which-3] = 2.1;
Referencing an Array: array_name[index] // indexed variable
Array index: 0 ≤ index ≤ sizeOfArray – 1.
Warning: Watch out for index out-of-range in array. index ≤ 0 or index ≥ sizeOfArray – 1
Example: The array examScores has indexed variables: examScores[0], examScores[1], examScores[2].
Accessing an Array Element:
Each element in an array can be used exactly as a “normal” variable of the base type:
homework[11] = 97; homework[13] = 76; int averageOf11And13 = 0.5 * (homework[11] + homework[13]);
Manipulating Array with For-Loop: for (int index = 0; index < sizeOfArray; index++) { statement1; statement2; … }
Initializing Array Variables:
This is equivalent to int b[3] = {168, 268, 368};
Q: What if we have the following declaration? int a[10] = {5, 5};
It will create an array a[] with 10 elements and initialize a[0] to 5, a[1] to 5, and a[2] through a[9] to 0.
Initialize/Process Arrays with for-loops:
const int numBuckets = 10; int bucketCount[numBuckets]; for (int i=0 ; i < numBuckets ; i++) bucketCount[i] = 0; // initialize array elts to 0's double score; cin >> score; // assume: 0<=score<= double threshhold = 90.0; for (int j = numBuckets - 1 ; j >= 0 ; j--) { // Be careful of array indices if (score >= threshhold) { bucketCount[j]++; break; } threshhold -= 10.0; }
Arrays in Functions: An indexed variable is just a variable whose type is the base type of the array, and may be used anywhere any other variable whose type is the base type of the array might be used. int i, n, a[10]; void my_function(int n); … my_function(n); my_function(a[3]);
Passing Array Element(s) to Function: void doWeirdThings(int a, int b, int& c) { a = 2a + b; b = 2b – a; c = (a + b) / 2; }
void callWeird() { int x = 7; int myArray[3] = {10, 20, 30}; doWeirdThings(x, myArray[0], myArray[2]); }
Consider: double average(int grades[104]) { double sum = 0.0; for (int i = 0 ; i < 104 ; i++) sum += grades[i]; return sum/104; }
It works but what happens when we have 107, or 93, homeworks?
Q: Do we have to write a separate “average” routine for each array size?
Good News : ° No, you don’t have to write separate average routines. ° C++ doesn’t pay any attention to the size that you declare for the array in the formal parameter! It just assumes you know what you’re doing. (This will be a little different when we get to multiply dimensioned arrays, but let’s not think about that right now.) The prototype would normally be written instead as: double average(int grades[ ]); In other words, we just tell the compiler that an array of integers of some size will be passed.
Q: But how do we implement the general average routine if we don’t know the size? A common convention is to pass the size as a parameter immediately following the array: double average(int grades[ ], int nGrades);
Then we would use this as: void myGrader() { int homework[104]; int exams[57]; int ages[32]; … double avgHW = average(homework,104); double avgExam = average(exams,57); double avgAge = average(ages,32); }
Remarks:
Example: void show_the_world( const int a[ ], int size_of_a) { cout << "Array values are:\n"; for ( int i = 0; i < size_of_a; a[i]++) // Error! cout << a[i] << " "; cout << endl; }
More Example : Suppose I’m debugging my average routine, and I want to use a display function for arrays.
void display(ostream& os, int nums[], int size) { os << ‘(‘; for (int i = 0 ; i < size ; i++) { os << nums[i]; if (i < (size-1)) os << “, ”; } os << “)\n”; } …
double average(const int values[], int nValues) { … display(os, values, nValues); double sum = 0.0; for (int i = 0 ; i < nValues ; i++) sum += values[i]; return sum/nValues; }
Q: What will happen?
Since the int array nums[] is not a constant array parameter in the display function, when called by the average function using a constant array parameter value[], an error message will be generated because display could possibly change the array parameter.
Warning: When passing arrays through several layers of functions, be sure that const arrays are only passed on where a const array parameter has been declared.
More Warning: Even though a function may return a value of primitive/class type, functions can not return array!
Consider
void func(int& a, double& b, int& c) { … }
void caller() { int x = 10, y = 20; double q = 1.1; func(x, y, static_cast
Since arrays are passed by address, we have similar problems: void func(int a[], double b[], int c[]) { … }
void caller() { int x[10], y[20]; double q[4]; func(x, y, static_cast<int[]>(q)); // Problem! }
Searching:
Given a partially filled array a[ ] of integers and an integer key (target). Returns the smallest index such that a[index] == target, if exists; otherwise, returns -1.
Sequential Search Algorithm: a[ ]: 0 1 2 size- …
target
int search(const int a[ ], int number_used, int target) { int index = 0; bool found = false; while ((!found) && (index < number_used)) if (target == a[index]) found = true; else index++; if (found) return index; else return -1; }