Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

home / study / engineering / computer science / questions and answers / lab 1- a

ID: 3672034 • Letter: H

Question

home / study / engineering / computer science / questions and answers / lab 1- a sequence class part a: implement a container ...

Your question has expired and been refunded.

We were unable to find a Chegg Expert to answer your question.

Question

Lab 1- A Sequence Class

Part A: Implement a container class called a sequence. The items contained in a sequence are arranged one after the other, unlike a bag, which implies an unorganized arrangement of items. The class should include member functions to allow a program to step through a sequence one item at a time, as well as member functions to control exactly where items are inserted and removed in the sequence. The class should include a data member that keeps track of the “current item” in the sequence and member functions to set the current item to the beginning of the sequence and to advance the current item. If there is a current item, then that item is in data[current_index]. Otherwise, current_index equals used.

You are provided with the header file (see page 2 of this document). You will code the implementation and driver as specified.

Your class should include the following constant and 3 private data members:

An array (data) to store the data in the sequence with a maximum capacity of 10 items.

A constant (CAPACITY) to hold the maximum capacity of the sequence (physical size).

A variable (used) to keep track of the number of items currently in the sequence.

A variable (current_index) to hold the index of the “current” item in the sequence (if there is one, i.e. the end of sequence has been found – out of bounds value).

Include the following features in your code:

Test your class with an interactive driver program that includes a menu feature to allow the user to choose operations to perform on an initially empty sequence and quit when desired. Also include a print function in your driver that will print the sequence in order (from position 0 through used -1) by calling the appropriate public member functions from the sequence class.

Break the program into 3 files- definition (.h), implementation(.cpp) and driver(.cpp).

Use the typedef statement to create a synonym for the array’s data type to make your code more flexible (see the PlainBox class in Chapter 1 for an example of using typedef).

Test your program with a sequence of ints and a sequence of char (you should only have to make one change in the typedef statement to do this).
Note: You need submit only one run to me.

All programs should include commenting, as well as indenting, spacing and variable/function names choices that improve readability. Submit a hard copy of all your code including output, and additionally email me all source and data files as attachments.

#ifndef SEQUENCE_H

#define SEQUENCE_H

    class sequence

    {

    public:

        typedef double value_type;

        static const int CAPACITY = 10;

        sequence( ); // Constructor – set used and current_index to 0

       

// MUTATOR MEMBER FUNCTIONS
//Postcondition: The first item in the sequence becomes the current item
void start( );

//Precondition: is_item returns true.

//Postcondition: If the current item was already the last item in the

//sequence, then there is no longer any current item. Otherwise, the new

//current item is the item immediately after the original current item.

        void advance( );

//Precondition: size( ) < CAPACITY.

//Postcondition: A new copy of entry has been inserted in the sequence

//before the current item. If there was no current item, then the new entry

//has been inserted at the front of the sequence (position 0). In either      //case, the newly inserted item is now the current item of the sequence.

        void insert(const value_type& entry);

//Precondition: size( ) < CAPACITY.

//Postcondition: A new copy of entry has been inserted in the sequence //after the current item. If there was no current item, then the new entry //has been attached to the end of the sequence. In either case, the newly

//inserted item is now the current item of the sequence.

        void attach(const value_type& entry);

//Precondition: is_item returns true.

//Postcondition: The current item has been removed from the sequence, and //the item after this (if there is one) is now the new current item.

        void remove_current( );

      

// ACCESSOR MEMBER FUNCTIONS

//Postcondition: The value returned is the number of items in the         //sequence.
int size( ) const;

//Postcondition: A true return value indicates that there is a valid

//"current" item that may be retrieved by invoking the current

//member function below. A false return value indicates that

//there is no valid current item.

        bool is_item( ) const{ return (current_index < used);}

//Precondition: is_item( ) returns true.

//Postcondition: The item returned is the current item in the sequence.

        value_type current( ) const;

    private:

        value_type data[CAPACITY];

        int used;

        int current_index;

    }; #endif

Explanation / Answer

sequence2.h


#ifndef MAIN_SAVITCH_SEQUENCE_H
#define MAIN_SAVITCH_SEQUENCE_H


namespace main_savitch_4
{
   typedef double value_type;

    class sequence
    {
    public:
        // TYPEDEFS and MEMBER CONSTANTS
      
        static const int DEFAULT_CAPACITY = 5;
        // CONSTRUCTORS and DESTRUCTOR
        sequence(int initial_capacity = DEFAULT_CAPACITY);
        sequence(const sequence& source);
       ~sequence( );
        // MODIFICATION MEMBER FUNCTIONS
       void resize(int new_capacity);
        void start( );
        void advance( );
        void insert(const value_type& entry);
        void attach(const value_type& entry);
        void remove_current( );
        void operator =(const sequence& source);
        // CONSTANT MEMBER FUNCTIONS
        int size( ) const;
        bool is_item( ) const;
        value_type current( ) const;
    private:
        value_type* data;
        int used;
        int current_index;
       int capacity;
    };
}

#endif

sequence2.cpp

#include "sequence2.h"

namespace main_savitch_4
{
   /*
   CONSTRUCTORS and DESTRUCTOR
   */

   // paramterized constructor
   sequence::sequence(int initial_capacity)
       :capacity(initial_capacity) //initialization list
   {
       //initialize data members
       used = 0;
       current_index = 0;
       //create dynamically-allocated array of size (capacity)
       data = new value_type[capacity];

   }//end sequence() parameterized constructor

   //copy constructor
   sequence::sequence(const sequence& source)
   {
       //initialize data members by copying values from sequence object passed in
       capacity = source.capacity;
       used = source.used;
       current_index = source.current_index;
       //create dynamically-allocated array of size (capacity)
       data = new value_type[capacity];
       //copy data elements from sequence object passed in
       for (int i = 0; i < used; i++)
       {
           data[i] = source.data[i];
       }
   }//end sequence() copy constructor

   //destructor
   sequence::~sequence()
   {
       //verify data array has been initialized and/or not previously deleted
       if (data != nullptr)
       {
           //delete[] dynamically allocated array
           delete[] data;
           data = nullptr;
       }
   }//end ~sequence() destructor

   /*
   MODIFICATION MEMBER FUNCTIONS
   */

   //resize()
   void sequence::resize(int new_capacity)
   {
       //new capacity is less than existing array size
       if (new_capacity < used)
       {
           //change capacity to be size of at least used portion of array
           new_capacity = used;
       }
       //copy data from old array into new temp array of size[capacity]
       value_type* tempPointer = new value_type[new_capacity];
       if (used > 0)
       {
           for (int i = 0; i < used; i++)
           {
               tempPointer[i] = data[i];
           }
       }
       //delete old dynamically allocated array
       delete[] data;
       //assign data pointer to new array
       data = tempPointer;
   }//end resize()

   //start()
   void sequence::start()
   {
       //set current_index value to 0 (first position - which is default value if no items in array)
       current_index = 0;
   }//end start()

   //advance()
   void sequence::advance()
   {
       //pre-condition: is_item() must be true
       assert(is_item());
       //increment current index by 1
       current_index++;
   }//end advance()

   //insert()
   void sequence::insert(const value_type& entry)
   {
       //pre-condition: number of items currently in array is less than current capacity
       assert(used < capacity);
       //if current_index is not an item
       if (!(is_item()))
       {
           //put (entry) value passed in into current_index element
           data[current_index] = entry;
       }
       //if current_item is an item
       else
       {
           //copy all data including current_index value into (current + 1) element making space for new item
           for (int i = used; i > current_index; i--)
           {
               data[i] = data[i - 1];
           }
           //put (entry) value passed in into current_index element
           data[current_index] = entry;
       }
       //increment used value
       used++;
   }//end insert()

   //attach()
   void sequence::attach(const value_type& entry)
   {
       //pre-condition: number of items currently in array is less than current capacity
       assert(used < capacity);
       //if current_index is not an item
       if (!(is_item()))
       {
           //put (entry) value passed in into current_index element
           data[current_index] = entry;

       }
       else
       {
           //copy all data after current_index value into (current + 1) element making space for new item
           for (int i = used; i > current_index + 1; i--)
           {
               data[i] = data[i - 1];
           }
           //put (entry) value passed in into current_index element (current_index is pre-incremented here)
           data[++current_index] = entry;
       }
       //increment used
       used++;
   }//end attach()

   //remove_current()
   void sequence::remove_current()
   {
       //pre-condition: is_item() must be true
       assert(is_item());
       //if there is/are item(s) in the array after current_index
       if (used > current_index + 1)
       {
           //move all items in array after current_index back to fill in space left when current_index data is removed
           for (int i = 0; i < ((used - 1) - current_index); i++)
           {
               data[current_index + i] = data[current_index + i + 1];
           }
       }
       //if no items exist in array after current _index
       else
       {
           //clear current_index data
           data[current_index] = NULL;
       }
       //decrement used
       used--;
   }//end remove_current()

   //overloaded operator =()
   void sequence::operator =(const sequence& source)
   {
       //verify that current object is not already an exact copy of sequence object being passed in
       if (this != &source)
       {
           //verify that dynamically allocated array data exists
           if (data != nullptr)
           {
               //delete existing array in current object
               delete[] data;
           }
           //initialize data members by copying values from sequence object passed in
           capacity = source.capacity;
           used = source.used;
           current_index = source.current_index;
           //create dynamically-allocated array of size (capacity)
           data = new value_type[capacity];
           //copy data elements from sequence object passed in
           for (int i = 0; i < used; i++)
           {
               data[i] = source.data[i];
           }
       }
   }//end operator =()

   /*
   CONSTANT MEMBER FUNCTIONS
   */

   //size()
   int sequence::size() const
   {
       //return current value of used data member
       return used;
   }//end size()

   //is_item()
   bool sequence::is_item() const
   {
       //return true/false value of whether current_index contains valid data
       return (!(used == 0 || current_index >= used));
   }//end is_item()

   //current()
   value_type sequence::current() const
   {
       //pre-condition: is_item() must be true
       assert(is_item());
       //return current value of element contained in current_index location
       return data[current_index];
   }//end current()

}//end namespace main_savitch_4


main.cpp

// FILE: sequence_test.cxx
// An interactive test program for the new sequence class
#include <cctype>       // Provides toupper
#include <iostream>     // Provides cout and cin
#include <cstdlib>      // Provides EXIT_SUCCESS
#include "sequence2.h" // With value_type defined as double
using namespace std;
using namespace main_savitch_4;

// PROTOTYPES for functions used by this test program:
void print_menu( );
// Postcondition: A menu of choices for this program has been written to cout.

char get_user_command( );
// Postcondition: The user has been prompted to enter a one character command.
// The next character has been read (skipping blanks and newline characters),
// and this character has been returned.

void show_sequence(sequence display);
// Postcondition: The items on display have been printed to cout (one per line).

double get_number( );
// Postcondition: The user has been prompted to enter a real number. The
// number has been read, echoed to the screen, and returned by the function.


int main( )
{
    sequence test; // A sequence that well perform tests on
    char choice;   // A command character entered by the user
  
    cout << "I have initialized an empty sequence of real numbers." << endl;

    do
    {
        print_menu( );
        choice = toupper(get_user_command( ));
        switch (choice)
        {
            case '!': test.start( );
                      break;
            case '+': test.advance( );
                      break;
            case '?': if (test.is_item( ))
                          cout << "There is an item." << endl;
                      else
                          cout << "There is no current item." << endl;
                      break;
            case 'C': if (test.is_item( ))
                           cout << "Current item is: " << test.current( ) << endl;
                      else
                          cout << "There is no current item." << endl;
                      break;
            case 'P': show_sequence(test);
                      break;
            case 'S': cout << "Size is " << test.size( ) << '.' << endl;
                      break;
            case 'I': test.insert(get_number( ));
                      break;
            case 'A': test.attach(get_number( ));
                      break;
            case 'R': test.remove_current( );
                      cout << "The current item has been removed." << endl;
                      break;   
            case 'Q': cout << "Ridicule is the best test of truth." << endl;
                      break;
            default: cout << choice << " is invalid." << endl;
        }
    }
    while ((choice != 'Q'));

    return EXIT_SUCCESS;
}

void print_menu( )
// Library facilities used: iostream.h
{
    cout << endl; // Print blank line before the menu
    cout << "The following choices are available: " << endl;
    cout << " !   Activate the start( ) function" << endl;
    cout << " +   Activate the advance( ) function" << endl;
    cout << " ?   Print the result from the is_item( ) function" << endl;
    cout << " C   Print the result from the current( ) function" << endl;
    cout << " P   Print a copy of the entire sequence" << endl;
    cout << " S   Print the result from the size( ) function" << endl;
    cout << " I   Insert a new number with the insert(...) function" << endl;
    cout << " A   Attach a new number with the attach(...) function" << endl;
    cout << " R   Activate the remove_current( ) function" << endl;
    cout << " Q   Quit this test program" << endl;
}

char get_user_command( )
// Library facilities used: iostream
{
    char command;

    cout << "Enter choice: ";
    cin >> command; // Input of characters skips blanks and newline character

    return command;
}

void show_sequence(sequence display)
// Library facilities used: iostream
{
    for (display.start( ); display.is_item( ); display.advance( ))
        cout << display.current( ) << endl;
}

double get_number( )
// Library facilities used: iostream
{
    double result;
  
    cout << "Please enter a real number for the sequence: ";
    cin >> result;
    cout << result << " has been read." << endl;
    return result;
}