7: Introduction to Arrays

What We Will Cover


Continuations

Homework Questions?

Questions from last class?

Given a single C++ class, which of the following functions can it have?

  1. foo(int a)
  2. foo(int a, int b)
  3. foo(double a)
  4. foo(double a, double b)
  5. foo(int b)

7.1: Arrays

Objectives

At the end of the lesson the student will be able to:

  • Declare and allocate memory for arrays
  • Write code to initialize arrays
  • Access array elements

Array: a single name for a collection of identically-typed data values

  • Arrays are a type of data structure
  • -- a way to organize data
  • An array is used to process a collection of data of the same type
    • Scores
    • Temperatures
  • Why do we need arrays?
  • Imagine keeping track of 5 test scores, or 100, or 1000 in memory
    • How would you name all the variables?
    • How would you process each of the variables?
  • Arrays provide a convenient solution to these problems
  • Entire array referred to by a single identifier
  • Each element uniquely identified by an index number

For Example

  • One-dimensional array is like single row of data in spreadsheet or table
  • score[0] score[1] score[2] score[3] score[4]
    90 95 87 89 98

  • Top row shows the indices for an array named "score"
  • Individual items are referenced by the index (a.k.a. subscript)
  • All the values are of the same type: int
  • Array length is 5

7.1.2: Declaring and Allocating Arrays

  • Consider an array named score containing 5 values
  • You declare and allocate memory for this array like this:
  • int score[5];
    
  • This is like declaring 5 variables of type int numbered as follows:
  • score[0], score[1], score[2], score[3], score[4]
  • The value in brackets is called an index or subscript
  • Individual values in an array are called items or elements
  • The number of indexed variables in an array is the size of the array
    • The largest index is one less than the size
    • The first index value is zero
  • Array declaration syntax:
  • DataType arrayName[length];
    
  • Arrays can be of any data type
  • All the variables of an array are always of the same data type
    • Known as the base type of the array
  • Once created, you cannot change the number of elements
  • The best way to specify the length of an array is to use a constant
  • const int NUMBER_OF_STUDENTS = 50;
    int score[NUMBER_OF_STUDENTS];
    
  • This allows you to know the length anywhere in your code
  • If you need to change the length, you change only a single constant and recompile

7.1.3: Referencing Array Elements

  • Each array element is referenced by name and an index inside of square brackets
  • score[3] is one of the indexed variables of the score array
  • score[0]++;
    
  • The index can be any integer expression
  • int n = 2;
    score[n + 1] = 99;
    
  • You can use an indexed array variable like any regular variable
  • score[0] = score[1] + 1;
    
  • Array elements referenced by the array name and index
  • Use the array operator [] to specify the index
  • Index must be an integer expression

7.1.4: Initializing Array Values

  • You can assign a value to an array element any time after it is declared
  • const int NUMBER_OF_STUDENTS = 5;
    int score[NUMBER_OF_STUDENTS];
    score[0] = 90;
    score[1] = 95;
    score[2] = 87;
    score[3] = 89;
    score[4] = 98;
    

Static Initialization

  • You can also initialize array elements in the declaration statement
    • Called initialization
    • Use a comma-separated list inside curly-braces
    int score[] = {90, 95, 87, 89, 98};
    
  • Produces the same array
  • Length of an array automatically determined from the initializer list
  • If you want a longer array with only the first few elements intialized, you can use:
  • int score[NUMBER_OF_STUDENTS] = {90, 95, 87};
    

7.1.5: Processing Array Values in a Loop

  • Array processing is easily done in a loop
  • A for loop is commonly used to process array elements
  • For example, to initialize array elements to a known value:
  • const int NUMBER_OF_STUDENTS = 5;
    int score[NUMBER_OF_STUDENTS];
    for (int i = 0; i < NUMBER_OF_STUDENTS; i++) {
        score[i] = 100;
        cout << i << ": " << score[i] << endl;
    }
    
  • Note the use of the constant length in the array loop

Initializing From the Keyboard

  • We can also use a loop to initialize values from the keyboard
  • const int NUMBER_OF_STUDENTS = 5;
    int score[NUMBER_OF_STUDENTS];
    cout << "Enter the score for each of the "
         << NUMBER_OF_STUDENTS << " students:\n";
    for (int i = 0; i < NUMBER_OF_STUDENTS; i++) {
        cin >> score[i];
    }
    
  • Note that the loop counter and array index counts from 0 to length - 1

Displaying an Array

  • Similarly, we can also use a loop to display the contents of an array
  • cout << "You entered:" << endl;
    for (int i = 0; i < NUMBER_OF_STUDENTS; i++) {
        cout << i << ": " << score[i] << endl;
    }
    

7.1.6: Array Index Out of Range

  • A common error is using a nonexistent index
  • Index values for int score[5] are the values 0 through 4
  • An index value not allowed by the array declaration is out of range
  • Using an out of range index value does not produce an error message!
  • For example, given the following code:
  • int a[6];
    int i = 7;
    a[i] = 238;
    
  • Executing the statement can cause any number of problems
  • One of the largest sources of bugs causing security problems

7.1.7: Summary

  • Arrays are convenient ways to process a list of data
  • You declare this array with a single statement:
  • DataType arrayName[size];
    
  • The best way to specify the size of an array is to use a constant
    • This allows you to know the size anywhere in your code
    • If you need to change the size, you change only a single constant
  • Each array element is referenced by name and an index inside of square brackets
  • You can use an indexed array variable like any regular variable
  • score[0] = score[1] + 1;
  • You can initialize array elements individually with an assignment statement
  • score[0] = 90;
  • A more convenient way is to use an initializer list
  • int score[NUMBER_OF_STUDENTS] = {90, 95, 87, 89, 98};
  • You can use loops to assign values to an array and to display array values
  • const int NUMBER_OF_STUDENTS = 5;
    int score[NUMBER_OF_STUDENTS];
    
    cout << "Enter the score for each of the "
         << NUMBER_OF_STUDENTS << " students:";
    for (int i = 0; i < NUMBER_OF_STUDENTS; i++) {
        cin >> score[i];
    }
    
    cout <<"You entered:");
    for (int i = 0; i < NUMBER_OF_STUDENTS; i++) {
        cout << score[i]);
    }
    
  • The programmer must be very careful to keep the array index within bounds
  • Accessing an array element outside the bounds of an array can cause many problems
    • However, there is no warning by the compiler
  • This is one of the largest sources of bugs causing security problems

Exercise 7.1

With a partner, if needed, take 5 minutes to complete the following:

  1. Start a text file named exercise7.txt.
  2. Prepare the exercise header as described in the HowTo on submitting exercises
  3. Label this exercise: Exercise 7.1
  4. Submit all exercises for today's lesson in one file unless instructed otherwise
  5. Write array declaration and allocation statements for the following descriptions and record them in your exercise7.txt file.

Array Descriptions

  1. A list of 100 integer grades
  2. A list of 25 characters
  3. A list of 50 double-precision values holding temperatures
  4. A list of 90 strings holding names

7.2: Arrays and Functions

Objectives

At the end of the lesson the student will be able to:

  • Pass arrays elements as arguments
  • Pass entire arrays as arguments
  • Use arrays in functions
  • Change array elements in functions

7.2.1: Array Elements as Arguments

  • Indexed variables can be arguments to functions
  • For example, if a program contains these declarations:
  • int i, n, a[10];
    void myFunction(int n);
    
  • You can use indexed variables a[0] through a[9] as arguments
  • myFunction(a[0]);
    myFunction(a[3]);
    myFunction(a[i]);
    

For Example

#include<iostream>
using namespace std;

const int NUMBER_ITEMS = 3;

/**
 * Displays a double to the screen
 */
void showPrice(double value);

int main(void) {
    double data[] = {12.3, 23.45, 3.456};
    for (int  i = 0; i < NUMBER_ITEMS; i++) {
        showPrice(data[i]);
    }
}

void showPrice(double value) {
    cout.setf(ios::fixed);     // fixed, not scientific
    cout.setf(ios::showpoint); // show decimal point
    cout.precision(2);         // show 2 decimal places
    cout << '$' << value << endl;
}

7.2.2: Arrays as Function Parameters

  • Can use an entire array as an argument to a function
  • When calling the array, use just the array name and no brackets
  • showArray(scores, NUMBER_OF_STUDENTS);
    
  • To pass an array, the function must have an array parameter
  • You declare an array parameter using empty brackets in the parameter list
  • void showArray(int values[], int size);
  • Following example shows an array used in a function:
  • void showArray(int values[], int length) {
        for (int i = 0; i < length; i++) {
            cout << values[i] << " ";
        }
    }
    
  • Note the use of the length variable
  • You do not know the length of the array that will be passed
  • Length of the array passed can be different for each call
  • So need to pass a length variable to the function
  • You could easily overload the showArray function for different array types

7.2.3: Changing Array Elements in Functions

  • Array parameters behave much like call-by-reference parameters
    • The function has access to and can change the original array
  • The values of the indexed variables can be changed by the function
  • You can even collect input in a function for an array

For Example:

#include<iostream>
using namespace std;

const int NUMBER_ITEMS = 3;

// Fills an array with int values from the keyboard
void fillUp(int a[], int size);

// Displays an array to the screen
void showArray(int a[], int size);

int main(void) {
    int data[NUMBER_ITEMS];
    fillUp(data, NUMBER_ITEMS);
    showArray(data, NUMBER_ITEMS);
}

void fillUp(int data[], int length) {
    cout << "Enter " << length << " numbers:\n";
    for (int i = 0; i < length; i++) {
        cin >> data[i];
    }
}

void showArray(int values[], int length) {
    cout << "You entered " << length << " numbers:\n";
    for (int i = 0; i < length; i++) {
        cout << values[i] << endl;
    }
}

Using the const Modifier

  • Normally, a function can change the values of array elements
  • You can prevent the modification using the const modifier
  • void showArray(const int values[], int length);
    
  • The compiler will issue error messages if you accidentally change an array element
  • For example, if you used const and made a mistake in showArray:
void showArray(const int values[], int length) {
    cout << "You entered " << length << " numbers:\n";
    for (int i = 0; i < size; values[i]++) {
        cout << values[i] << endl;
    }
}
  • Using const, the compiler gives us a message like:
  • fillup.cpp: In function `void showArray(const int*, int)':
    fillup.cpp:27: increment of read-only location
    
  • If a function with a constant array parameter calls another function using the const array parameter as an argument...
    • The called function must use a const array parameter as well
    • Otherwise, the compiler will issue an error

7.2.4: Returning an Array

  • Recall that functions can return a value of type int, double, char, or even a class type like string
  • However, functions cannot return arrays
  • We learn later how to return a pointer to an array

7.2.5: Summary

  • Indexed variables can be arguments to functions
  • You can also pass an entire array as an argument to a function
  • To pass an array, the function must have an array parameter
  • void showArray(int a[], int size);
  • Important to pass the size of the array as well
  • Array parameters behave much like call-by-reference parameters
  • The function has access to and can change the original array
  • You can prevent the modification using the const modifier
  • void showArray(const int a[], int size);
  • Functions cannot return arrays

Exercise 7.2

  1. Label this exercise: Exercise 7.2
  2. Submit all exercises for today's lesson in one file unless instructed otherwise
  3. Complete the following and record the answers to any questions in exercise7.txt.

Specifications

  1. The following declarations were used to create an array referenced by the variable grades:
  2. const int NUMGRADES = 500;
    double grades[NUMGRADES];
    

    Write a function declaration for a function named sortArray which has a parameter for the array grades shown above. Add any other formal parameters needed to the function and record your solution in exercise7.txt.

  3. Write a function definition named oneMore which has a parameter for an array of int's and adds one to each element of the array. Add any other formal parameters needed to the function and record your solution in exercise7.txt.

7.3: Programming With Arrays

Objectives

At the end of the lesson the student will be able to:

  • Use partially-filled arrays to solve the fixed-array-size problem
  • Test array equality
  • Compute statistics on arrays of data
  • Search an array
  • Sort an array
  • Choose the best algorithm for searching an array

7.3.1: Using Arrays Interactively

Partially-Filled Arrays

  • You often do not know how large to make an array
  • Needs can vary from one run of a program to another
  • A common solution to this size problem is to:
    1. Declare the array size to be the largest that could ever be needed
    2. Use code that can deal with partially-filled arrays
  • Note that functions may not need to know the size of the array
  • May be enough to know only how many elements are stored in the array

For Example

/*
 * Shows the difference between each of a list of scores
 * and their average.
 */
#include <iostream>
using namespace std;

const int MAX_NUMBER_SCORES = 10;

/**
 * Partially fills an array and returns the number
 * of elements used.
 */
void fillArray(int a[], int size, int& numberUsed);

/**
 * Returns the average of numbers a[0] through
 * a[numberUsed - 1]
 */
double computeAverage(const int a[], int numberUsed);

/**
 * Displays how much each of the first numberUsed
 * elements differ from their average
 */
void showDifference(const int a[], int numberUsed);

int main(void) {
    int score[MAX_NUMBER_SCORES], numberUsed;

    cout << "This program reads scores and shows how\n"
         << "much each differs from the average.\n";

    fillArray(score, MAX_NUMBER_SCORES, numberUsed);
    showDifference(score, numberUsed);

    return 0;
}

void fillArray(int a[], int size, int& numberUsed) {
    cout << "Enter up to " << size
         << " nonnegative whole numbers.\n"
         << "Enter a negative number when finished.\n";

    int next, index = 0;
    cin >> next;
    while ((next >= 0) && (index < size)) {
        a[index] = next;
        index++;
        cin >> next;
    }

    numberUsed = index;
}

double computeAverage(const int a[], int numberUsed) {
    double total = 0;
    for (int index = 0; index < numberUsed; index++)
        total = total + a[index];
    if (numberUsed > 0) {
        return (total / numberUsed);
    } else {
        cout << "ERROR: number of elements is 0.\n"
             << "computeAverage returns 0.\n";
        return 0;
    }
}

void showDifference(const int a[], int numberUsed) {
    double average = computeAverage(a, numberUsed);
    cout << "Average of the " << numberUsed
         << " scores = " << average << endl
         << "The scores are:\n";
    for (int index = 0; index < numberUsed; index++) {
        cout << a[index] << " differs from average by "
             << (a[index] - average) << endl;
    }
}
  • Function fillUp needs to know the array size
  • Other functions only need to know how many elements to use
  • Note that when function fill_array is called, MAX_NUMBER_SCORES is an argument
  • Why not use MAX_NUMBER_SCORES directly without passing it as an argument?
    • Using MAX_NUMBER_SCORES as an argument makes it clear that fillArray requires the array's declared size
    • This makes fillArray easier to use in other programs

7.3.2: Testing Array Equality

Using == With Array Names

  • Remember that arrays store values in sequential memory locations
  • Thus, different arrays store values in different memory locations
  • Tests using == checks if the memory addresses are the same
  • if (a == b)
    

For Example

    #include <iostream>
    using namespace std;
    
    int main() {
        int a[] = {1, 2, 3};
        int b[] = {1, 2, 3};
        if (a == b) {
            cout << "a == b\n";
        } else {
            cout << "a != b\n";
        }
    
        return 0;
    }
    
  • Both arrays have the same elements
  • However, they are stored at different locations in memory
  • Thus, they do not have the same memory address

Testing Array Elements for Equality

  • To test array elements for equality, need to check each element
  • Define an equals function that returns true if and only if all the array elements are equal
  • Arrays must also be the same length
  • Updating our previous code:
  • #include <iostream>
    using namespace std;
    
    const int NUM_ELEMENTS = 3;
    
    bool equals(int a[], int b[], int length);
    
    int main() {
        int a[] = {1, 2, 3};
        int b[] = {1, 2, 3};
        if (a == b) {
            cout << "a == b\n";
        } else {
            cout << "a != b\n";
        }
        if (equals(a, b, NUM_ELEMENTS) == true) {
            cout << "a equals b\n";
        } else {
            cout << "a not equal to b\n";
        }
    
        return 0;
    }
    
    bool equals(int a[], int b[], int length) {
        for (int i = 0; i < length; i++) {
            if (a[i] != b[i]) {
                return false;
            }
        }
        return true;
    }
    

7.3.3: Calculating Statistics on Arrays

  • You can use a loop to sum every item in an array
  • #include<iostream>
    using namespace std;
    
    const int NUMBER_ITEMS = 5;
    
    int main(void) {
        int data[] = {1, 2, 3, 4, 5};
        int sum = 0;
        for (int i = 0; i < NUMBER_ITEMS; i++) {
            sum = sum + data[i];
            cout << data[i] << ", ";
        }
        cout << "\nsum = " << sum << endl;
    }
    
  • What code would we add to show the average of the array values?
  • What would we change to find the maximum array value?
  • How would we find the minimum array value?
  • What is the easiest way to initialize minimum and maximum values?

Restricting the Range

  • We can choose to calculate statistics over a portion of an array
  • For example, the following finds a minimum between start and end
  • Note that it does not return a value, but rather an array index
  • You use the array index to look up the minimum value
int findMin(const int data[], int start, int end) {
    int indexOfMin = start;
    for (int i = start + 1; i <= end; i++) {
        if (data[i] < data[indexOfMin]) {
            indexOfMin = i;
        }
    }
    return indexOfMin;
}

7.3.4: Searching an Array

  • Many techniques for searching an array for a particular value
  • Sequential search:
    • Start at the beginning of the array
    • Compare each value in sequence
    • If value is found, then exit
    • Continue until you reach the end of the array
    #include<iostream>
    using namespace std;
    
    const int NUMBER_ITEMS = 5;
    const int VALUE_TO_FIND = 9;
    
    int main(void) {
        int data[] = {12, -3, 9, -5, 10};
    
        bool found = false;
        int count = 0;
        while ((!found) && (count < NUMBER_ITEMS)) {
            if (VALUE_TO_FIND == data[count]) {
                found = true;
            }
            count++;
        }
    
        if (found) {
            cout << "Found ";
        } else {
            cout << "Not found ";
        }
        cout << VALUE_TO_FIND << " in " << count
             << " comparisons\n";
    }
    
  • Would it be any faster to start searching at the end of an array?
  • If an array is sorted, then we can program faster functions -- binary search

7.3.5: Sorting an Array

  • Sorting is a common task for computers, for example:
    • Sort numbers in ascending order
    • Sort numbers in descending order
    • Sort strings in alphabetic order
  • Many different algorithms for sorting, including:
    • Bubble sort - move item up until in right place
    • Insertion sort - add elements to list one at a time
    • Selection sort - pick 1st, then 2nd, etc.
    • Quick sort - divide and conquer

Selection Sort

  • Selection sort is one of the easiest -- but not the most efficient
  • General algorithm:
    1. Find the smallest element
    2. Swap with the first element
    3. Find the smallest element in the rest of the list
    4. Swap with the first element of the rest of the list
    5. Repeat until the list is sorted

    Pass a[0] a[1] a[2] a[3] a[4] a[5] a[6]
    Original 10 7 29 14 -4 -12 21
    First -12 7 29 14 -4 10 21
    Second -12 -4 29 14 7 10 21
    Third -12 -4 7 14 29 10 21
    Fourth -12 -4 7 10 29 14 21
    Fifth -12 -4 7 10 14 29 21
    Sixth -12 -4 7 10 14 21 29

  • How many passes were needed for a seven element array?

Selection Sort Code

  • Following is selection sort code
  • Have added some statements to show action for each pass
#include <iostream>
using namespace std;

const int NUMBER_ITEMS = 7;

/**
 * Sorts the array so that
 * a[0] <= a[1] <= ... <= a[numberUsed - 1]
 */
void sort(int data[], int numberUsed);

/**
 *Interchanges the values of variable1 and variable2.
 */
void swapValues(int& variable1, int& variable2);

/**
 * Returns the index i such that data[i] is the
 * smallest value between data[start] and data[end].
 */
int findMin(const int data[], int start, int end);

/**
 * Displays an array to the screen
 */
void showArray(int a[], int length);

int main() {
    int a[] = {10, 7, 29, 14, -4, -12, 21};

    cout << "Original: ";
    showArray(a, NUMBER_ITEMS);
    sort(a, NUMBER_ITEMS);
    cout << "\nSorted array:   ";
    showArray(a, NUMBER_ITEMS);
    cout << endl;

    return 0;
}

void sort(int data[], int numberUsed) {
    int indexOfMin;
    //Place the correct value in a[index]:
    for (int index = 0; index < numberUsed - 1; index++) {
        indexOfMin =  findMin(data, index, numberUsed);
        swapValues(data[index], data[indexOfMin]);
        cout << "Pass#" << index << ": ";  // tracing
        showArray(data, numberUsed);       // tracing
    }
}

void swapValues(int& variable1, int& variable2) {
    cout << "\nSwapping " << variable1
         << " with " << variable2 << endl; // tracing
    int temp = variable1;
    variable1 = variable2;
    variable2 = temp;
}


int findMin(const int data[], int start, int end) {
    int indexOfMin = start;
    for (int i = start + 1; i <= end; i++) {
        if (data[i] < data[indexOfMin]) {
            indexOfMin = i;
        }
    }
    return indexOfMin;
}

void showArray(int values[], int length) {
    for (int i = 0; i < length; i++) {
        cout << values[i] << "  ";
    }
}
  • Note that every element in the array must have a value
  • Can the array have duplicate items?
  • Also note that the larger task was broken into smaller tasks using functions
    • Helps to organize program and improve clarity

What About Bubble Sort?

  • Another sorting algorithm that is easy to understand and use
  • General algorithm:
    1. Make length passes through the array
    2. For each pass, compare each array element with the next element
    3. If the current element is larger than the next one, swap them
  • Not an efficient sorting algorithm
  • Sometimes simple algorithms perform poorly
  • Simple algorithms are still useful: easy to program and understand
  • If better performance is needed, replace with a better algorithm
  • More information: Sorting Algorithms

7.3.6: Binary Search

  • Once an array is sorted, can use binary search to find an item
  • Binary search is much faster than sequential search

Binary Search Algorithm

  • A key value is searched for among the values stored in the array.
  • Two index variables lowIdx and highIdx are used to limit the scope of the search.
  • The search proceeds until the element searched for is found or the scope between lowIdx and highIdx is exhausted.
    • The index middleIdx is computed as (lowIdx + highIdx) / 2.
    • If key = data[middleIdx] the search is successful.
    • If key < data[middleIdx], highIdx is lowered to middleIdx.
    • If key > data[middleIdx], lowIdx is raised to middleIdx.
    • If the scope between lowIdx and highIdx is exhausted, the search is unsuccessful.
  • Visual demonstration: BinarySearch

Binary Search Code

#include <iostream>
using namespace std;

const int NUMBER_ITEMS = 7;

/**
 * Find the index of key in array a
 * return -1 if key is not found
 */
int binarySearch(int a[], int length, int key);

/**
 * Displays an array to the screen
 */
void showArray(int a[], int length);

int main(void) {
    int a[] = {-12, -4, 7, 10, 14, 21, 29};

    int key = 14;
    cout << "Searching array: ";
    showArray(a, NUMBER_ITEMS);
    int index = binarySearch(a, NUMBER_ITEMS, key);
    cout << "Index of " << key << " = "
         << index << endl;
}

int binarySearch(int a[], int length, int key) {
    int step = 0; // tracing
    int lowIdx = 0;
    int highIdx = length - 1;
    int middleIdx;
    while (lowIdx <= highIdx) {
        step++;
        middleIdx = (lowIdx + highIdx) / 2;
        cout << "Step#" << step
             << " lowIdx=" << lowIdx
             << " highIdx=" << highIdx
             << " middleIdx=" << middleIdx
             << endl; // tracing
        if (a[middleIdx] == key) {
            return middleIdx;        // just right
        } else if (a[middleIdx] < key) {
            lowIdx = middleIdx + 1;  // too small
        } else {
            highIdx = middleIdx - 1; // too big
        }
    }
    return -1; // not found
}

void showArray(int values[], int length) {
    for (int i = 0; i < length; i++) {
        cout << values[i] << "  ";
    }
    cout << endl;
}

How Much Faster is Binary Search?

  • Given the sorted array:
  • a[0] a[1] a[2] a[3] a[4] a[5] a[6]
    -12 -4 7 10 14 21 29

  • How many steps to find the value of 14 using sequential search?
  • How many steps to find the value of 14 using binary search?
  • On average for an array of n elements:
    • Sequential search takes n / 2 steps
    • Binary search takes 2 * log2(n) + 2 steps maximum
  • Translating to some array sizes:
  • Array Size floor(log2(n)) + 1
    1 1
    10 4
    100 7
    1000 10
    10,000 14

  • Binary search quickly becomes worth the effort of its implementation
  • Binary search is one algorithm a programming professional should know!

7.3.7: Summary

  • You can easily enter values into an array for later processing
  • A "partially filled array" is one in which values are stored in an initial segment of the array
  • Arrays work well with loops to sum data and calculate other statistics
  • You can search arrays sequentially to find a value
  • Sorting algorithms can sort an array into ascending or descending order
  • If an array is sorted, can use binary search to speed the search process

Exercise 7.3

  1. Label this exercise: Exercise 7.3
  2. Submit all exercises for today's lesson in one file unless instructed otherwise
  3. Complete the following and record the answers to any questions in exerciseX.txt.

Specifications

Show the contents of the following array after each pass of SelectionSort. Record the results in exercise7.txt.

int[] array = {9, 21, -7, 2, 87, -19, 47}

7.4: Midterm Preparation

Objectives

At the end of the lesson the student will be able to:

  • Discuss how to prepare for the first midterm exam
  • Describe how to take the first midterm exam

7.4.1: About the Exam

  • You must attend the exam or you will receive a score of zero (0)
    • Except by prior arrangement with the instructor
  • I am using WebCT to administer the test
  • Since their are more students than computers, we must take the exams in shifts
  • Shifts are determined by your last name as follows:
    • Shift 1: A-K (starts at the regular class time)
    • Shift 2: L-Z (starts half way through regular class time)
  • You must come to the classroom when your shift is scheduled
    • Except by prior arrangement with the instructor
    • You may have less time if you are late to your scheduled time
  • The exam is closed books and closed notes
    • However, you may have one 3" x 5" card of notes for the exam
    • You must turn in your 3" x 5" card after the exam
  • You may use your computer, but only to take the exam in WebCT
  • You may have a sheet of blank scratch paper
  • You may NOT use the computer to compile or run programs
  • You may NOT use the computer to view documents on the Internet
  • You may NOT use a calculator or other electronic device
  • You may NOT communicate with anyone but the instructor during the exam

7.4.2: Recommended Preparation

  • Work through the Practice Midterm Exam questions in WebCT
    • Working the problems in groups is encouraged
    • Get explanations for anything you do not understand
  • Review your notes and prepare your 3" x 5" card
  • Review your homework assignments and solutions
  • Review your CodeLab exercises
  • You should be prepared to write short programs
    • Mathematical expressions
    • Conditional statements
    • Ask-first loops
    • Counter-controlled loops
    • Sentinel-controlled loops
    • Function declarations
    • Call-by-value function definitions
    • Call-by-reference function definitions
    • User I/O
  • A few more tips:
    • I avoid using true/false questions
    • I try to use questions containing actual code
  • More quiz tips: TAKING MULTIPLE –CHOICE TESTS

7.4.3: Exam Taking Tips

  • Save after every answer -- you can always choose another answer
  • If you get stuck on a question, make your best guess and return later
  • If you are equally uncertain between two choices, go with first impression
  • You do not need to comment code for tests and exams
    • Unless specifically instructed to in the exam question
  • Use the full time available
    • Use any remaining time to check your work

7.4.4: Questions and Answers

  • Any questions?

Wrap Up

Home | WebCT | Announcements | Day Schedule | Eve Schedule
Course info | Help | FAQ's | HowTo's | Links

Last Updated: October 26 2004 @15:46:18