CS35: Quiz 1 Study Guide

You should be able to define or explain the following terms:

You should be familiar with all aspects of basic C++ programs, such as those you created for labs 01 and 02. This includes:

Practice problems

  1. Write a C++ program that prompts the user for an integer n and then prints a single output integer, the sum of the integers from 1 to n.

  2. Write a boolean function isPrimaryColor that takes a string as an argument and returns true if the string is "red", "yellow", or "blue", and returns false otherwise. Then write a program that prompts the user for a color and uses isPrimaryColor to determine if their color is primary.

  3. Consider the code in examples/week03/destructor/safeArray.cpp. Draw the stack diagram caused by the execution of the following code
    myarray.setElement(7,15);
    
    just before the "unsafe operation" performed by the code. Include the stack and the heap.

  4. Write a Person abstract class with the following features:
    • appropriate public getName(), getAge() and print() accessor functions. These should be pure virtual functions.
    Then write a Student subclass of Person with the following features:
    • a private name (string), age (int), major (string) and gradYear (int)
    • a constructor which takes a name, age, and grad, which it uses to initialize the data members, except the major which is initialized to "Undecided".
    • in addition to the methods prescribed by the base class, the Student object should have methods setMajor, getMajor and getGradYear. The print function should print on screen a message like: "Siona is a 20 year old Economics major who will graduate in 2019."
    Finally, write a main() function that declares a pointer p to a Person, creates a single Student on the heap and saves the pointer to that Person as p, and then prints the Person and releases its memory.

  5. Write a C++ function that takes an array of integers and its size, and returns true if and only if the array contains at least 5 odd numbers.

  6. Add a distance method to the MyPoint class in examples/week03/pointers/ that takes a MyPoint as input and returns the distance between that MyPoint and the MyPoint from which the method was called. To implement this, you will need the sqrt function from the cmath library.

  7. Add your favorite dog breed to examples/week02/fromdClass/dog. Then, in main.cpp, in the main function, statically allocate an array of 5 Dog pointers, and in a loop, ask the user which breed of dog to create for each bucket of the array (asking any additional relevant information if necessary). Then, in a separate loop, make all the dogs bark. After this, release all the dynamically allocated memory, and use Valgrind to make sure you did not forget any.