Homework 2: Working with Arrays
Due: Thursday, September 21, 8:59:59pm
Instructions: In each of the three questions below, you are asked to write a short C++ progam. Place the programs in files called q1.cpp, q2.cpp and q3.cpp. On GL, in the script command, compile each program and run each program under valgrind. You should have one typescript file for the three programs. Then, copy the four files q1.cpp, q2.cpp, q3.cpp and typescript to the hw2 subdirectory in your submission directory.
Question 1
In the main() function below, we have an array of 10 pointers to objects of class Two. Fill in the rest of the code that has a for loop which allocates memory for each entry of the array and initializes the members part1 and part2 to 0. This program does not have any output.
Question 2
In the main() function below, we use a function called initialize() that allocates memory for an array of int. The size of the array is given by the second parameter to initialize. The array must be initialized so the i th item of the array has value i. (See sample output below.) The first parameter must be passed by reference and modified by the initialize() function to point to the newly allocated array.
Implement the initialize function so it is compatible with the main() function as given. Yes, part of the question here is to figure out the function signature for initialize().
Question 3 (Adapted from R-3.14 of textbook.)
This question was re-written for clarification. -RC
In the code below, the srand() function from cstdlib is used to set the random seed of a pseudo-random number generator. After that, you can call the rand() function to obtain a "random" number:
Implement the printRandom() function that repeatedly selects and "removes" a random entry from the array C and then prints out the selected value until all values in the array C have been printed. Each value from the array should be printed exactly once. It is OK to modify the array C. The first parameter of printRandom() is the array to be printed, the second parameter is the size of the array and the third parameter is the radom seed to be used.
If we ran the main program below, which calls printRandom() three times with different random seeds, we might get output that looks like: