Question

In: Computer Science

Files I need to be edited: I wrote these files and I put them in a...

Files I need to be edited: I wrote these files and I put them in a folder labeled Project 7. I am using this as a study tool for a personal project of mine.

//main.cpp

#include <iostream>

#include "staticarray.h"

using namespace std;

int main( ) {

   StaticArray a;

   cout << "Printing empty array -- next line should be blank\n";

   a.print();

   /*

   // Loop to append 100 through 110 to a and check return value

   // Should print "Couldn't append 110"

   cout << "\nTesting append: Should print error message for 110 only\n";

   for (int i = 100; i < 111; i++) {

       if (!(a.append(i))) {

           cout << "Couldn't append " << i << endl;

       }

   }

   cout << "\nShould print 100 through 109 below:\n";

   a.print();

   //Declaration of indices

   int indices[] = { 9, 3, 5, 0 };

   // Loop to access some arbitrary elements of a

   cout << "\nTesting member function -at- :\n";

   cout << "Should print 109 103 105 100\n";

   for (int i = 0; i < 4; i++) {

       cout << a.at(indices[i]) << " ";

   }

   cout << endl;

   // Save me from myself

   cout << "Should print -11111 and not crash:\n";

   cout << a.at(10000000) << endl;

   // Testing sum

   cout << "\nTesting sum: Should print 1045\n";

   cout << a.sum() << endl;

   // Test remove:

   //  Remove (a) 102

   //         (b) 111 (should return false)

   cout << "\nTesting remove. If you don't see 'Uh-oh,' that's a good sign.\n";

   if (!a.remove(102)) cout << "Uh-oh, can't remove 102\n";

   if (a.remove(111)) cout << "Uh-oh, shouldn't be able to remove 111\n";

   cout << "Updated print: should print 100 101 103 104 105 106 107 108 109\n";

   a.print();

   cout << endl;

   // Test remove and append together:

   cout << "\nTesting remove and append together.\n";

   a.remove(109);

   a.remove(108);

   a.append(278);

   cout << "Final print: should print 100 101 103 104 105 106 107 278\n";

   a.print();

   cout << endl;

   */

   return 0;

}

//staticarray.cpp

#include <iostream>

#include "staticarray.h"

using namespace std;

// Print all array elements

void StaticArray::print() {

  for (int i = 0; i < len; i++) {

     cout << arr[i] << " ";

     if (i % 10 == 9) {

         cout << endl; // newline every 10 elements

     }

  }

}

//staticarray.h

const int MAX = 10;

class StaticArray {

public:

   ~StaticArray() { } // destructor - ignore for now

   void print();

private:

   int arr[MAX]; //array with capacity of MAX elements

   int len; //current number of elements in the array

};

CMakeLists.txt

cmake_minimum_required(VERSION 3.14)

project(lab07)

set(CMAKE_CXX_STANDARD 14)

add_executable(lab07 main.cpp staticarray.cpp)

Process to follow:

You should now have 3 files. Read each of these files, in the order listed below.

  • staticarray.h -- contains the class definition for StaticArray, which makes arrays behave a little more like Python listsIn particular, pay attention to the private variables. Note that the array has been defined with a MAX capacity but that is not the same as having MAX elements. Which variable indicates the actual number of elements in the array?
  • staticarray.cpp -- contains function definitions for StaticArray. Right now, that's just the print() member function.Pay attention to the print() function. How many elements is it printing?
  • main.cpp -- client code to test your staticarray class.Note that the multi-line comment format (/* ... */) has been used to comment out everything in main below the first print statement. As you proceed through, can you move the starting (/*) to a different location. Other than that, no changes must be made to main.cpp.

Default Constructor:

The first step is to write the default constructor, which should initialize the array to empty by specifying that currently there are no elements in it. You can get away with just one line of code inside this function.

On a piece of paper, write down the prototype for this function. Put the prototype into the public section of the class definition in staticarray.h.

StaticArray();

In staticarray.cpp, write the function definition. Remember, just one line!

At this point, you should compile and run the code. The output statements in the main will tell you what to expect.

Append:

Define an append() member function, which should do 2 things:

  1. If there's room in the array (how can you determine this?), append the given value to the end of the array
  2. Return true if the value was appended and false if the array was full.

Then put the prototype into the public section of the class definition in staticarray.h.

bool append(int value);

In staticarray.cpp, write the function definition. Alas, this is more than just one line.

In main.cpp, put the code that tests append (up to the declaration of indices) back into your code. Compile and check the output to make sure everything is correct so far.

At:

The at() member function is going to work just like the brackets notation for arrays. It gets passed an index, and should return the element at that index. In other words, arr.at(0) is like our version of arr[0].

If the index is outside the bounds of the array, it should return -11111 (an arbitrary default value). The ability to perform this is a nice benefit vs. regular arrays.

Write the prototype for the at function, and then check below:

int at(int index);

Again, add the prototype to the .h and the function definition to the .cpp. Then add everything up to "Testing sum" back into main.

Sum:

Again, add the prototype to the .h and the function definition to the .cpp. Then add everything up to "Testing sum" back into main.

int sum();

Remove:

pass this function the value you want to remove, and then delete the first array element equal to that value. In the example below, we have the values 200 through 209 in an array, and we pass 203 to remove:(len is 10 before calling remove)

200 201 202 203 204 205 206 207 208 209

Here's what the array should look like after deletion. Note that, because the length is 9, we will consider the second 209 as arbitrary garbage; it's past the end of the array we're modeling.

200 201 202 204 205 206 207 208 209 prob 209 but it doesn't matter

(len is now 9)

This function should return true if the delete was successful, and false if the value didn't match any array element. For example, for this array, remove(214) should return false.

Create and double-check the prototype:

bool remove(int value);

Then add this function to the class, and run the original main, with all tests back in.

The programs that must be tested are the StaticArray.cpp and StaticArray.h

They are being tested with the edited main.cpp.

Solutions

Expert Solution

Answer 1: variable len indicates the actual number of elements in the array .

Answer 2: print() function is printing total element present in array(indicated by variable len).

Below is completed code. Let me know if you have any problem or doubt. Thank you

===============================================================

staticarray.h

======================

const int MAX = 10;
class StaticArray {
public:
    StaticArray(); // default constructor
    ~StaticArray() { } // destructor - ignore for now
    void print();
    // returns true if the value was appended and false if the array was full
    bool append(int value);
    // returns element from from array at given index
    // returns -11111 if index is out of bound
    int at(int index);
    // returns sum of all elements from array
    int sum();
    // removes given element from array
    // return true if element is removed otherwise return false if element is not in array
    bool remove(int value);
private:
    int arr[MAX]; //array with capacity of MAX elements
    int len; //current number of elements in the array
};

======================

staticarray.cpp

======================

#include <iostream>
#include "staticarray.h"
using namespace std;

StaticArray::StaticArray() {
    // initialize the array to empty by specifying that currently there are no elements in it
    len = 0;
}

// Print all array elements
void StaticArray::print() {
    for (int i = 0; i < len; i++) {
        cout << arr[i] << " ";
        if (i % 10 == 9) {
            cout << endl; // newline every 10 elements
        }
    }
}

bool StaticArray::append(int value) {
    // check if array have space to add value
    // array is full if total number of elements in array are equal to MAX
    if (len < MAX) {
        arr[len] = value; // add value at end of array
        len++; // increase total number of elements in array
        return true;
    }
    return false;
}

int StaticArray::at(int index) {
    // check for valid index
    if (index >= 0 && index < len) {
        return arr[index];
    }
    else {
        return -11111;
    }
}

int StaticArray::sum() {
    int result = 0;
    // create a loop to add all elements in result
    for (int i = 0; i < len; i++) {
        result = result + arr[i];
    }
    return result;
}

bool StaticArray::remove(int value) {
    // loop over array to find the given value
    for (int i = 0; i < len; i++) {
        if (arr[i] == value) {
            // value found at current index
            // to remove the value move each element from array after cuurent
            // index to one place left
            for (int j = i + 1; j < len; j++) {
                arr[j - 1] = arr[j];
            }
            // reduce total number of elements in array
            len--;
            return true;
        }
    }
    return false;
}

======================

main.cpp

======================

#include <iostream>
#include "staticarray.h"
using namespace std;

int main() {
    StaticArray a;
    cout << "Printing empty array -- next line should be blank\n";
    a.print();

    // Loop to append 100 through 110 to a and check return value
    // Should print "Couldn't append 110"
    cout << "\nTesting append: Should print error message for 110 only\n";
    for (int i = 100; i < 111; i++) {
        if (!(a.append(i))) {
            cout << "Couldn't append " << i << endl;
        }
    }
    cout << "\nShould print 100 through 109 below:\n";
    a.print();

    //Declaration of indices
    int indices[] = { 9, 3, 5, 0 };
    // Loop to access some arbitrary elements of a
    cout << "\nTesting member function -at- :\n";
    cout << "Should print 109 103 105 100\n";
    for (int i = 0; i < 4; i++) {
        cout << a.at(indices[i]) << " ";
    }
    cout << endl;

    // Save me from myself
    cout << "Should print -11111 and not crash:\n";
    cout << a.at(10000000) << endl;

    // Testing sum
    cout << "\nTesting sum: Should print 1045\n";
    cout << a.sum() << endl;

    // Test remove:
    // Remove (a) 102
    //         (b) 111 (should return false)
    cout << "\nTesting remove. If you don't see 'Uh-oh,' that's a good sign.\n";
    if (!a.remove(102)) cout << "Uh-oh, can't remove 102\n";
    if (a.remove(111)) cout << "Uh-oh, shouldn't be able to remove 111\n";
    cout << "Updated print: should print 100 101 103 104 105 106 107 108 109\n";
    a.print();
    cout << endl;

    // Test remove and append together:
    cout << "\nTesting remove and append together.\n";
    a.remove(109);
    a.remove(108);
    a.append(278);
    cout << "Final print: should print 100 101 103 104 105 106 107 278\n";
    a.print();
    cout << endl;

    return 0;
}

======================

CMakeLists.txt

======================

cmake_minimum_required(VERSION 3.14)
project(lab07)
set(CMAKE_CXX_STANDARD 14)
add_executable(lab07 main.cpp staticarray.cpp)

===============================================================

Below is screenshot of output for the code.


Related Solutions

I wrote this code and just realized I need to put it into at least 6...
I wrote this code and just realized I need to put it into at least 6 different functions and I don't know how. No specific ones but recommended is: Read Data, Calculate Installation Price, Calculate Subtotal, Calculate Total, Print -> 1) Print Measurements & 2) Print Charges. Can somebody help? #include <stdio.h> // Function Declarations int length, width, area, discount; int main () { // Local Declarations double price, cost, charge, laborCharge, installed, amtDiscount, subtotal, amtTax, total; const double tax...
I need this in java on textpad. There are two files, both have instructions in them...
I need this in java on textpad. There are two files, both have instructions in them on what to add in the code. They are posted below. public class MyArrayForDouble { double[] nums; int numElements; public MyArrayForDouble() { // Constructor. automatically called when creating an instance numElements = 0; nums = new double[5]; } public MyArrayForDouble(int capacity) { // Constructor. automatically called when creating an instance numElements = 0; nums = new double[capacity]; } public MyArrayForDouble(double[] nums1) { nums =...
I have a product I need to market in the Kingdom of Saudi Arabia I wrote...
I have a product I need to market in the Kingdom of Saudi Arabia I wrote most of the main points but it remains only for me: Marketing Mix (4 P’s ) Analysis Describe each of the 4Ps of your chosen company. Product or Service Identify the product or service by what it is, who will buy it, how much they will pay for it and how much it will cost for the company to produce it, why a consumer...
I don't know if you have the stats for this but I tried to put them...
I don't know if you have the stats for this but I tried to put them in here and it told me this is too long. I do not have Minitab so I would need it in Excel please and thank you so much. It will not let me put all the info in here. Says its too long. Refer to the Baseball 2016 data, which report information on the 30 Major League Baseball teams for the 2016 season. a....
​​​​​Need to find these on a search engine and put each of them from low to...
​​​​​Need to find these on a search engine and put each of them from low to high end need help. Intel High-End Desktop Microprocessor Series Core Operating Frequency Cache FSB (or Equivalent) Intel Low-End Desktop Microprocessor Series Core Operating Frequency Cache FSB (or Equivalent) AMD High-End Desktop Microprocessor Series Core Operating Frequency Cache FSB (or Equivalent) AMD Low-End Desktop Microprocessor Series Core Operating Frequency Cache FSB (or Equivalent) Microprocessor Definitions Series Cores Operating Frequency Cache FSB (or Equivalent) High-End Desktop...
I need the ex1 and ex2 files written out. The book is "in a byte of...
I need the ex1 and ex2 files written out. The book is "in a byte of python" basics chapter. I can copy and paste WORKING CODE into an editor. Thank you! 1.     In A Byte of Python        - read and test Basics chapter in python intrepreter 2.     create a source file; run a program in Terminal        - copy "Example: Using Variables And Literal Constants" from Basics chapter        - attach identifying comment (in all your future programs)        - save the file...
i need an example of a program that uses muliple .h and .cpp files in c++...
i need an example of a program that uses muliple .h and .cpp files in c++ if possible.
I need to suggest and wrote Three things you have learned about what is important in...
I need to suggest and wrote Three things you have learned about what is important in life during this time of the pandemic, that you wish to carry forward with you. Please write only what you are comfortable sharing with others. You may also include a link to poem, a photo, a song . . 150word acount .
I have n books with n different titles. I want to put them on the shelves...
I have n books with n different titles. I want to put them on the shelves in my library. How many different ways are there to arrange them on one shelf? On two shelves? On k shelves?
I have been trying to upload a png file I edited with the information required, the...
I have been trying to upload a png file I edited with the information required, the editor's message is " URL missing" but then I can't type in anything in that cell. Please help. 4.31 Calculate the enthalpy change or the heat of the following reactions at 298oC by using the values from Standard Enthalpies and Free Energies of formation at 298oC. Please, if you must use values form another tabulation please specify and comment. a) 2HI(g) → H2(g) +...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT