Docsity

C++ Array Declaration, Initialization, and Manipulation, Study notes of Electrical and Electronics Engineering

Toggle sidebar
bg1
1
L8-Arrays
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
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20

Partial preview of the text

Download C++ Array Declaration, Initialization, and Manipulation and more Study notes Electrical and Electronics Engineering in PDF only on Docsity!

L8-Arrays

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:

  • Used to store and organize large number of data objects.
  • Allow repeated execution of the same data.
  • Allow random accessing of data through indexing.

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:

  • Recall that a simple variable can be initialized in one statement: Example : int sum = 0;
  • A variable of array, struct, or class type is a compound variable. A compound variable can also be initialized with one statement Example : struct init_example { int a; int b; }; init_example x = {1, 2};
  • An array can be initialized like we initialize a struct: int children[3] = {2, 12, 1};
  • The compiler can also count for you: int b[ ] = {168, 268, 368};

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:

  • Arrays can never be passed by value. They are effectively passed by reference, although the C/C++ terminology is to say it is “passed by address”. (In the book, this is also described as array argument/parameter passing. )
  • The elements of array arguments changed inside a function will also change the array arguments in the calling environment, just like pass by reference parameters.

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(q)); // Problem! }

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; }