Question

In: Computer Science

IN C++ (THIS IS A REPOST) Design a class, Array, that encapsulates a fixed-size dynamic array...

IN C++ (THIS IS A REPOST)

Design a class, Array, that encapsulates a fixed-size dynamic array of signed integers.

Write a program that creates an Array container of size 100 and fills it with random numbers in the range [1..999]. (Use std::rand() with std::srand(1).) When building the array, if the random number is evenly divisible by 3 or 5, store it as a negative number.

Within your main.cpp source code file, write a function for each of the following processes.

  1. Print the array ten values to a line. Make sure the values are aligned in columns. Each column should have a width of 5.
  2. Return the sum of all values in the array.
  3. Return the address of the smallest value in the array.

Requirements

Demonstrate each of the functions above and several of the Array class member functions in your main function.

Need 3 files Array.h, Array.cpp, main.cpp

You must use the interface provided below. Do not modify any function signatures. Do not use any form of base+offset addressing within repetition structures (i.e., use pointers to traverse the array).

Array Class Interface (Array.h)

#ifndef ARRAY_H_
#define ARRAY_H_

#include <cstddef>

class Array {
public:
    /// Default constructor. Constructs a new container with 'count' copies of
    /// elements with value 'value'.
    /// @param count The number of elements.
    /// @param value Value to fill each element.

    Array(std::size_t count, int value = 0);

    /// Copy constructor. Constructs the Array with a copy of the
    /// contents of 'other'.
    /// @param other Array to copy.

    Array(const Array& other);

    /// Free the resources used by the container.

    virtual ~Array();

    /// Returns a reference to the element at specified position 'pos'.
    /// @param pos Position of the element to return.
    /// @return Reference to the requested element.

    int& at(std::size_t pos);
    const int& at(std::size_t pos) const;

    /// Returns a reference to the first element in the container.
    /// Calling front on an empty container is undefined.
    /// @note For a container c, the expression 'c.front()' is equivalent
    /// to '*c.begin()'.
    /// @return Reference to the first element.

    int& front();
    const int& front() const;

    /// Returns a reference to the last element in the container.
    /// Calling back on an empty container is undefined.
    /// @note For a container c, the expression return 'c.back()' is equivalent
    /// to '{ auto tmp = c.end(); --tmp; return *tmp; }'
    /// @return Reference to the last element.

    int& back();
    const int& back() const;

    /// Returns a pointer to the first element of the container.
    /// If the container is empty, the returned pointer will be equal to 'end()'
    /// @return Pointer to the first element.

    int* begin() { return m_list; }
    const int* begin() const { return m_list; }

    /// Returns a pointer to the element following the last element of the
    /// container. This element acts as a placeholder; attempting to dereference
    /// this pointer is undefined.
    /// @return Pointer to the element following the last element.

    int* end() { return m_list + size(); }
    const int* end() const { return m_list + size(); }

    /// Checks if the container has no elements, i.e., whether
    /// 'begin() == end()'.
    /// @return true if the container is empty, false otherwise.

    bool empty() const;

    /// Returns the number of elements in the container, i.e., the distance
    /// between 'begin()' and 'end()'.
    /// @return The number of elements in the container.

    std::size_t size() const { return m_size; }

    /// Assigns the given value 'value' to all elements in the container.
    /// @param value The `value` to assign to the elements.

    void fill(int value);

    /// Exchanges the contents of this container with another.
    /// @param other Container to exchange the contents with.

    void swap(Array& other);
    
protected:
    std::size_t m_size;  ///< Number of elements allocated.
    int*        m_list;  ///< Pointer to base of array.
};

// Non-Member Function(s)

/// Compares the contents of two arrays. Returns true if the contents of
/// lhs and rhs are equal, that is, whether each element in lhs compares
/// equal with the element in rhs at the same position.
/// Otherwise, returns false.
/// @param lhs Container to compare.
/// @param rhs Container to compare.
/// @return true if lhs and rhs compare equal, otherwise false.

bool equal(const Array& lhs, const Array& rhs);

#endif  // ARRAY_H_ 

/* EOF */

Solutions

Expert Solution

// Array.h
#ifndef ARRAY_H_
#define ARRAY_H_

#include <cstddef>

class Array {
public:
/// Default constructor. Constructs a new container with 'count' copies of
/// elements with value 'value'.
/// @param count The number of elements.
/// @param value Value to fill each element.

Array(std::size_t count, int value = 0);

/// Copy constructor. Constructs the Array with a copy of the
/// contents of 'other'.
/// @param other Array to copy.

Array(const Array& other);

/// Free the resources used by the container.

virtual ~Array();

/// Returns a reference to the element at specified position 'pos'.
/// @param pos Position of the element to return.
/// @return Reference to the requested element.

int& at(std::size_t pos);
const int& at(std::size_t pos) const;

/// Returns a reference to the first element in the container.
/// Calling front on an empty container is undefined.
/// @note For a container c, the expression 'c.front()' is equivalent
/// to '*c.begin()'.
/// @return Reference to the first element.

int& front();
const int& front() const;

/// Returns a reference to the last element in the container.
/// Calling back on an empty container is undefined.
/// @note For a container c, the expression return 'c.back()' is equivalent
/// to '{ auto tmp = c.end(); --tmp; return *tmp; }'
/// @return Reference to the last element.

int& back();
const int& back() const;

/// Returns a pointer to the first element of the container.
/// If the container is empty, the returned pointer will be equal to 'end()'
/// @return Pointer to the first element.

int* begin() { return m_list; }
const int* begin() const { return m_list; }

/// Returns a pointer to the element following the last element of the
/// container. This element acts as a placeholder; attempting to dereference
/// this pointer is undefined.
/// @return Pointer to the element following the last element.

int* end() { return m_list + size(); }
const int* end() const { return m_list + size(); }

/// Checks if the container has no elements, i.e., whether
/// 'begin() == end()'.
/// @return true if the container is empty, false otherwise.

bool empty() const;

/// Returns the number of elements in the container, i.e., the distance
/// between 'begin()' and 'end()'.
/// @return The number of elements in the container.

std::size_t size() const { return m_size; }

/// Assigns the given value 'value' to all elements in the container.
/// @param value The `value` to assign to the elements.

void fill(int value);

/// Exchanges the contents of this container with another.
/// @param other Container to exchange the contents with.

void swap(Array& other);

protected:
std::size_t m_size; ///< Number of elements allocated.
int* m_list; ///< Pointer to base of array.
};


// Non-Member Function(s)

/// Compares the contents of two arrays. Returns true if the contents of
/// lhs and rhs are equal, that is, whether each element in lhs compares
/// equal with the element in rhs at the same position.
/// Otherwise, returns false.
/// @param lhs Container to compare.
/// @param rhs Container to compare.
/// @return true if lhs and rhs compare equal, otherwise false.

bool equal(const Array& lhs, const Array& rhs);

#endif // ARRAY_H_

//end of Array.h

// Array.cpp
#include "Array.h"
#include <iostream>
#include <stdexcept>

using namespace std;

Array::Array(std::size_t count, int value)
{
// set m_size to count
m_size = count;
// check that m_size is not negative, if negative set it to 0
if(m_size < 0 )
m_size = 0;

// size > 0
if(m_size > 0){
// create an array of int of size
m_list = new int[m_size];

int *p = m_list; // set p to starting address

// loop to populate array with value
for(; p != end(); ++p)
{
*p = value;
}
}
else // size = 0
m_list = nullptr;
}


Array::Array(const Array& other)
{
// set size to other's size
m_size = other.m_size;
if(m_size > 0) // size > 0
{
// allocate array of size
m_list = new int[m_size];

// populate array to other's elements
int *p = begin();
size_t i = 0;
for(; p != end();++p, ++i)
*p = other.at(i);
}
else
m_list = nullptr;
}

Array::~Array()
{
if(m_list != nullptr) // not null, release the memory allocated
delete [] m_list;
}

int& Array::at(std::size_t pos)
{
// invalid index
if(pos < 0 || pos >= m_size)
throw out_of_range( "Position out of range" );
return m_list[pos]; // valid index
}

const int& Array:: at(std::size_t pos) const
{
// invalid index
if(pos < 0 || pos >= m_size)
throw out_of_range( "Position out of range" );
return m_list[pos]; // valid index
}

int& Array:: front()
{
if(!empty()) // not empty
return m_list[0];
else // empty array
throw out_of_range( "Array is empty" );
}

const int& Array::front() const
{
if(!empty()) // not empty
return m_list[0];
else // empty array
throw out_of_range( "Array is empty" );
}

int& Array:: back()
{
if(!empty()) // not empty
return m_list[m_size-1];
else // empty array
throw out_of_range( "Array is empty" );
}

const int& Array:: back() const
{
if(!empty()) // not empty
return m_list[m_size-1];
else // empty array
throw out_of_range( "Array is empty" );
}

bool Array:: empty() const
{
return m_size == 0;
}

void Array:: fill(int value)
{
int * p = begin(); // set p to start of array
// loop over the array setting all elements to value
for(; p != end() ; ++p)
*p = value;
}

void Array:: swap(Array& other)
{
// set temp to m_list address
int *temp = m_list;
int temp_size = m_size; // set temp_size to m_size

// update m_size to other's size and m_list to other's m_list
m_size = other.m_size;
m_list = other.m_list;

// update other's m_size and m_list to temp_size and temp array
other.m_size = temp_size;
other.m_list = temp;

}

bool equal(const Array& lhs, const Array& rhs)
{
if(lhs.size() == rhs.size()) // size equal
{
// loop over the array, comparing each corresponding elements
for(size_t i=0;i<lhs.size();i++)
{
if(lhs.at(i) != rhs.at(i)) // ith element not equal, return false
return false;
}

return true; // arrays are equal
}

return false; // arrays are not equal
}

// end of Array.cpp

// main.cpp : C++ program to create an Array of size 100, populate with elements in range [1,999] and perform operations on the array
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include "Array.h"
using namespace std;

// function declaration
void display(Array& obj);
int sum(Array& obj);
int* min(Array& obj);

int main()
{
srand(1);
int num;
Array arr(100); // create an array of size 100

// loop to populate the random integers
for(int i=0;i<100;i++)
{
num = rand()%1000+1; // generate an integer between [1, 999]
if(num%3 == 0 || num%5 == 0) // num is divisible by 3 or 5, set it as negative num
arr.at(i) = -num;
else
arr.at(i) = num; // else set it as positive num
}

// display the array
cout<<"Array: "<<endl;
display(arr);
// display the sum of all elements
cout<<endl<<"Total of all elements: "<<sum(arr)<<endl;
// display address of minimum element
cout<<"Minimum element address: "<<min(arr)<<endl;

return 0;
}

// function to display the elements of array
void display(Array& obj)
{
int *p = obj.begin(); // set p to first element of array
int count = 0;
// loop over the array displaying 10 elements in a line
for(;p != obj.end(); ++p)
{
cout<<setw(5)<<*p;
count++;
if(count%10 == 0)
cout<<endl;

}
}

// function to compute the total of all elements of the array
int sum(Array& obj)
{
int total = 0;
int *p = obj.begin(); // set p to start of array
// loop over the array, summing the elements of array
for(; p!=obj.end();++p)
total += (*p);
return total;
}

// function to return the address of minimum element
int* min(Array& obj)
{
int* minElem = obj.begin(); // set minimum element address as the first element
int *p = obj.begin(); // set p to first element address
// loop over the array
for(; p != obj.end();++p)
{
if((*p) < (*minElem)) // p < minElem, set minElem to p
minElem = p;
}
return minElem;
}

// end of main.cpp

Output:


Related Solutions

Implement in C++ Design a BookstoreManager class which creates a dynamic array of type Book (don’t...
Implement in C++ Design a BookstoreManager class which creates a dynamic array of type Book (don’t use vectors), and provide an implementation for the following operations on books in the array 1)isEmpty() returns true if the array is empty, otherwise false 2)isFull() returns true if the array is full, otherwise false 3)listSize() prints the number of books in the array 4)print() prints the content of the array 5)insert(Book) asks the user to enter new book info, and it adds the...
Implement in C++ Design a BookstoreManager class which creates a dynamic array of type Book (don’t...
Implement in C++ Design a BookstoreManager class which creates a dynamic array of type Book (don’t use vectors), and provide an implementation for the following operations on books in the array 1)isEmpty() returns true if the array is empty, otherwise false 2)isFull() returns true if the array is full, otherwise false 3)listSize() prints the number of books in the array 4)print() prints the content of the array 5)insert(Book) asks the user to enter new book info, and it adds the...
please use C++ Create a class named Byte that encapsulates an array of 8 Bit objects....
please use C++ Create a class named Byte that encapsulates an array of 8 Bit objects. The Byte class will provide the following member functions: Byte - word: Bit[8] static Bit array defaults to all Bits false + BITS_PER_BYTE: Integer16 Size of a byte constant in Bits; 8 + Byte() default constructor + Byte(Byte) copy constructor + set(Integer): void sets Bit to true + clear(): void sets to 0 + load(Byte): void sets Byte to the passed Byte + read():...
Write a code in c++ using dynamic array of structure and dynamic array list. Make a...
Write a code in c++ using dynamic array of structure and dynamic array list. Make a dummy list for a company which stores following information about its customers. Customer ID Customer Name Gender Total items purchased Item category 20% discount in percentage of total purchase amount. Use dynamic array to save at least 20 items by dividing them into 3 different categories. Make a dummy list of items that company sells by dividing them into two categorizes. Items has following...
Implement a class Polynomial that uses a dynamic array of doubles to store the coefficients for...
Implement a class Polynomial that uses a dynamic array of doubles to store the coefficients for a polynomial. Much of this work can be modelled on the C++ dynamic array of ints List that we discussed in class. This class does not need the method the overloaded += operator. Your class should have the following methods: Write one constructor that takes an integer n for the degree of a term and a double coefficient c for the coefficient of the...
For this assignment you will implement a dynamic array. You are to build a class called...
For this assignment you will implement a dynamic array. You are to build a class called MyDynamicArray. Your dynamic array class should manage the storage of an array that can grow and shrink. The public methods of your class should be the following: MyDynamicArray(); Default Constructor. The array should be of size 2. MyDynamicArray(int s); For this constructor the array should be of size s. ~MyDynamicArray(); Destructor for the class. int& operator[](int i); Traditional [] operator. Should print a message...
c++ I need a code that will fill an array size of 1000, an array of...
c++ I need a code that will fill an array size of 1000, an array of size 2000, and an array size of 10000, with random int values. Basically like this: array1[1000] = filled all with random numbers array2[2000] = filled all with random numbers array3[10000] = filled all with random numbers C++ no need for print
write a c++ program. Define a class ‘Matrix’ which contain 2D int array ‘m’ of size...
write a c++ program. Define a class ‘Matrix’ which contain 2D int array ‘m’ of size 3x3 as private member.        There should be two public methods within the class definition namely: void setMatrixValue(int i, int j); that should set m[i][j] with user defined values int getMatrixValue(int i, int j); that should return m[i][j] Make a global function named ‘CrossProduct(Matrix m1, Matrix m2)’ that should compute the marix multiplication
For this lab you will continue your dynamic array by completing the class called MyDynamicArray. The...
For this lab you will continue your dynamic array by completing the class called MyDynamicArray. The MyDynamicArray class should manage the storage of an array that can grow and shrink. The public methods of your class should already be the following: MyDynamicArray(); Default Constructor. The array should be of capacity 2. MyDynamicArray(int s); For this constructor the array should be of capacity and size s. int& operator[](int i); Traditional [] operator. Should print a message if i is out of...
In c++ Array expander Write a function that accepts an int array and the arrays size...
In c++ Array expander Write a function that accepts an int array and the arrays size as arguments. The function should create a new array that is twice the size of the argument array. The function should create a new array that is twice the size of the argument array. The function should copy the contents of the argument array to the new array and initialize the unused elements of the second array with 0. The function should return a...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT