CSCE 2004 - Laboratory Assignment 11

The objective of this laboratory assignment is to build upon the experience you have gained from the previous lab in using classes and objects. It has the following steps:

  1. Using the SafeArray class
  2. In this part, you are given the header file for a SafeArray class below.

    Step 1: Save this in a file called SafeArray.h.

    
    #include <string>
    
    
    
    using namespace std;
    
    
    
    const int SIZE = 20;
    
    class SafeArray
    
    {
    
         public:
    
    	 SafeArray();
    
             float getElement (const int i, bool &success);
    
             float getElement (const int i, bool &success);
    
             void sort();
    
             void print();
    
             void readArray (const string filename);
    
             void writeArray (const string filename);
    
         private:
    
             float array[SIZE];
    
    };
    
    

    The above class implements an array of 20 float values and several methods to manipulate the array. Take the time to read through the class declaration. Because it provides array bounds checking before accessing the array elements, it is a safe array implementation.

    The method descriptions are as follows:

    1. readArray(): Reads the 20 float values into the array.
    2. sortArray(): Sorts the array in ascending order.
    3. getElement(): Returns the element of the array whose index we pass as the argument to the function. Sets the reference variable we pass to the function (as type bool) from main() to 'false' if the index we provide is out of the array bounds. Otherwise, sets it to 'true'.
    4. setElement(): Takes input from the user and sets it as the element of the array whose index we pass as the argument to the function. Sets the reference variable (type bool) we pass to the function from main to 'false' if the index we provide is out of bounds. Otherwise sets it to 'true'.
    5. print(): Prints the array to the screen.
    6. writeArray(): Writes the (presumably, modified) array to the file again.
    7. SafeArray(): A class constructor that will initialize the array values to zeros.

    The method implementations are given below.

    Step 2: Save this in a file called SafeArray.cpp.

    
    #include <iostream>
    
    #include <cstdlib>
    
    #include <fstream>
    
    
    
    #include <string>
    
    #include "SafeArray.h"
    
    
    
    using namespace std;
    
    
    
    float SafeArray::getElement(const int i, bool &success)
    
    {
    
            if(i < SIZE && i >= 0)
    
            {
    
                    success = true;
    
                    return array[i];
    
            }
    
            else
    
            {
    
                    success = false;
    
                    cerr << "Array index out of bounds!" << endl;
    
                    return -1;
    
            }
    
    }
    
    
    
    SafeArray::SafeArray()
    
    {
    
    	for(int i = 0; i < SIZE; i++)
    
    	{
    
    		Array[i] = 0.0;
    
    	}
    
    }
    
    
    
    float SafeArray::setElement(const int i, bool &success)
    
    {
    
            if(i < SIZE && i  >= 0)
    
            {
    
                    success = true;
    
                    cout << "Enter the value for array variable" << i << " :";
    
                    cin >> array[i];
    
                    return array[i];
    
            }
    
            else
    
            {
    
                    success = false;
    
                    cerr << "Array index out of bounds!" << endl;
    
                    return -1;
    
            }
    
    }
    
    
    
    void SafeArray::sort()
    
    {
    
            float temp = 0.0;
    
            for(int i = 0; i < SIZE; i++)
    
    	{
    
            	for(int j = i+1; j < SIZE; j++)
    
    		{
    
            		if (array[j] < array[i])
    
            		{
    
    	        		temp = array[i];
    
            			array[i] = array[j];
    
    	        		array[j] = temp;
    
    			}
    
    		}
    
            }
    
    }
    
    
    
    void SafeArray::print()
    
    {
    
            for(int i = 0; i < SIZE; i++) 
    
    		cout << "Value: " << i << " in the array is: "
    
                         << array[i] << endl;
    
    }
    
    
    
    void SafeArray::readArray(const string filename)
    
    {
    
            float temp;
    
            int i = 0;
    
            ifstream din;
    
    
    
    	din.open(filename.c_str());
    
    	if(!din)
    
            {
    
                    cerr << "Error opening file: " << filename << endl;
    
                    exit(1);
    
            }
    
    	else
    
    	{
    
            	din >> temp;
    
            	while(!din.eof() && i < SIZE)
    
            	{
    
                    	array[i] = temp;
    
                    	i++;
    
                    	din >> Temp;
    
            	}
    
            	din.close();
    
    	}
    
    }
    
             
    
    void SafeArray::writeArray(const string filename)
    
    {
    
            int i = 0;
    
            ofstream dout;
    
    	dout.open(filename.c_str());
    
            if(!dout)
    
            {
    
            	cerr << "Error opening file: " << filename << endl;
    
    		exit(1);
    
    	}
    
    	else
    
    	{
    
            	while(i < SIZE)  
    
            	{
    
                    	dout << array[i] << endl;
    
                    	i++;
    
            	}
    
            	dout.close();
    
    	}
    
    }
    
    
    
    

    Step 3: You should create an Empty File named "floats.txt" with 20 arbitrary floating-point values on 20 lines.

    Now, your task is to write a main() program that calls the class's methods as defined above to do the following, in order:

    1. Read the floats into the array from the file.
    2. Print the array to screen.
    3. Set an element in the array by specifying an index and an input value.
    4. Get an element from the array using an index.
    5. Sort the array in ascending order.
    6. Write the modified array back to the file.

    Step 4: In main.cpp, make sure that you #include the SafeArray.h file. Then, declare an object of type SafeArray. At this step, the program should not actually call any methods from the SafeArray class - it should compile properly with just the object declaration and the required return 0; in the main body.

    Step 5: Add in a call to a method for just the first task in the list above. Compile and test it.

    Step 6: Add in calls to the other methods one at a time. Compile and test after adding each. Work your way down the list one at a time.

  3. Developing the SafeArray class
  4. In this part you will be adding a new private instance variable, int numUsed;, to the 'SafeArray' class so that you can work on an array with number of elements less than twenty unlike the previous time when you worked with an array with a fixed size of 20. The 'numUsed' variable should be set to the number of floats read from the file. Additionally, we will modify the declarations of SafeArray so that the array is dynamically allocated.

    Step 1: Modify the functions of the class so that they work with 'numUsed' instead of 'SIZE' and hence work better with files which have number of floats totaling less than twenty.

    Edit floats.txt so that it contains only 10 numbers. Run your main program from before (without modification) to check that it works properly with your new addition.

    Step 2: Modify the private variable of SafeArray so that it has a pointer to a float (named 'array') instead of a statically allocated array of floats. Change 'SIZE' from a global constant to a private variable of the SafeArray class. In the SafeArray constructor, set the initial value of SIZE to 10.

    Finally, add code at the end of the SafeArray constructor to dynamically allocate an array of floats of size 'SIZE' using the float pointer private variable.

    Step 3: Add a private method, double(), to the SafeArray class that doubles the size of the internal array without losing any data stored in the array. Modify the readArray() method to call double() as needed to support whatever file size is read in.

  5. Adding a layer: classes in classes
  6. In this section you are given a new class called GradeBook that has three methods:

    (1) default constructor,
    (2) print method
    (3) fillGradeBook method

    Step 1: Save this in a file called GradeBook.h.

    
    class GradeBook
    
    {
    
    	public:
    
    		GradeBook(); //default class constructor
    
    		void print(); //This function will print three values and then calls the SafeArray print() function
    
    		int fillGradeBook(const string filename); //This function will fill the GradeBook from a file, ask the user
    
                                                              //for dept-code, CourseNumber, and it returns the number of
    
    							  //grades	
    
    	private:
    
    		string dept_code;
    
    		int course_number;
    
    		int num_grades;
    
    		SafeArray grades;
    
    };
    
    
    
    

    Step 2: Save this in a file called GradeBook.cpp.

    
    #include <iostream>
    
    #include <fstream>
    
    #include "GradeBook.h"
    
    
    
    using namespace std;
    
    
    
    GradeBook::GradeBook()
    
    {
    
    	dept_code = "";
    
    	course_number = 0;
    
    	num_grades = 0;
    
    }
    
    
    
    void GradeBook::print()
    
    {
    
    	cout << "Department Code: " << dept_code << endl 
    
    	     << "Course Number: " << course_number << endl
    
    	     << "Number of grades: " << num_grades << endl;
    
    	grades.print();
    
    }
    
    
    
    int GradeBook::fillGradeBook(const string filename)
    
    {
    
       // This method sets all the private instance variables
    
       // It fills the GradeBook from a file by calling a method of SafeArray
    
       // It PROMPTS the user for dept_code and course_number (eg, cout/cin), 
    
       // It returns the number of grades read in from the file (and assigns the same
    
       // value to the private variable, num_grades
    
    }
    
    
    
    

    Step 3: Save this in a file called lab11b.cpp.

    
    #include <iostream>
    
    #include <fstream>
    
    #include "GradeBook.h"
    
    
    
    using namespace std;
    
    
    
    int main()
    
    {
    
    	GradeBook book1;
    
    
    
    	return 0;
    
    }
    
    
    
    
    Step 4: Remove your previous main.cpp from the project (lab11b.cpp replaces it).

    Step 5: Check that your project compiles with the new program lab11b.cpp.

    Step 6: Fill the body of the fillGradeBook with the appropriate code. Test that it properly fills every private variable of the GradeBook (including the SafeArray variable). You should use your previous file of floats to test.

  7. Submit Your Work
  8. To submit your lab work, have your TA check over any code/output that you've done during this lab session and record that you completed the lab assignment.

    Important Note: It is your responsibility, not the TA's, to ensure that your lab is recorded as being completed before you leave! Although the labs are intended to be completed in the alloted lab time, if you need additional time to finish the lab assignment, you have 24 hours from the end of the lab meeting time to finish. If so, you should ask your TA for instructions on how to submit the lab assignment after the lab ends.

  9. Logout of the System
  10. After making sure that you submitted the code correctly and you have done the entire assignment, logout of the system by clicking on the menu button in the lower left hand side of the desktop. Then, click on Log Off. Wait a few seconds for a window to pop up and then click Log Off.