Data Structures and Algorithms

Test 1 Study Guide

The first test in this course may contain any material covered in lecture up until this point, although much stronger emphasis will be placed on material for which you have received graded feedback. This page contains a collection of exercises that you may wish to complete to prepare yourself for the test.

Programming in C++

  1. Write a function average which computes the average of the values in an array of floats. You must take a float* parameter; you may take other parameters as you see fit. Your function should return the average of the values in that array.

  2. Write a function fibonacci which takes a parameter int n and returns an int* to a new array which contains the first n Fibonacci numbers (0, 1, 1, 2, 3, 5, 8, 13, …).

  3. Write a function zerowash which allocates space for a million int values, sets them all to 0, and then releases the memory.

  4. Explain the difference between delete and delete[].

Debugging C++

Each of the following code fragments contains a bug. Identify the bug and explain how to correct it.

  1. Code to create an array of ten elements and set each element equal to its index.

    int* array = new int[10];
    for (int i=0;i<10;i++) {
        *array = i;
    }
    
  2. Code to define a function which sums all of the values in an array.

    int sum(int* array) {
        int acc = 0;
        for (int i=0;i<len(array);i++) {
            acc += array[i];
        }
        return acc;
    }
    
  3. Code to define a class which represents a single (X,Y) coordinate.

    class Point {
    public:
        Point(int x, int y);
        int get_x();
        int get_y();
    private:
        int x;
        int y;
    }
    Point::Point(int x, int y) {
        x = x;
        y = y;
    }
    int Point::get_x() {
        return x;
    }
    int Point::get_y() {
        return y;
    }
    

Object-Oriented Programming

  1. Define polymorphism as it pertains to C++. Give an example which was not given in lecture.

  2. What is a destructor? Why do we use them?

  3. Draw a stack diagram of the following code when it reaches the end of main. Be sure to be clear what is on the stack and what is on the heap.

    class LabAssignment {
    public:
        LabAssignment(int number, int score);
        int number;
        int score;
    }
    LabAssignment::LabAssignment(int number, int score) {
        this->number = number;
        this->score = score;
    }
    
    int main(int argc, char** argv) {
        LabAssignment a(1,98);
        LabAssignment* b = new LabAssignment(2,84);
        LabAssignment* c = b;
        b = new LabAssignment(3,95);
        c->score = 92;
        return 0;
    }