SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,kenrick Mock
Chapter:
Structures And Classes
Exercise:
Programming Projects
Question:2 | ISBN:9780132846813 | Edition: 5

Question

Define a class for a type called CounterType . An object of this type is used to count things, so it records a count that is a nonnegative whole number. Include a mutator function that sets the counter to a count given as an argument. Include member functions to increase the count by one and to decrease the count by one. Be sure that no member function allows the value of the counter to become negative. Also, include a member function that returns the current count value and one that outputs the count. Embed your class definition in a test program.


TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

#include <iostream>

using namespace std;

/**

class definition for CounterType

*/

class CounterType {

private:

    // private variables

    int count;

    int counter = 0;

public:

    // default constructor

    CounterType() { count = 0; }

    // constructor which accept count value and

    // set the value to count

    CounterType(int c) { count = c; }

    // incrementing counter

    void increseCounter() { counter++; }

    // decreasing the count

    int decreaseCount() {

        // if count reach to then returning false

        if (count == 0)

            return 0;

        count--;

        return 1;

    }

    // methods for get count and get counter

    int getCount() { return count; }

    int getCounter() { return counter; }

    // method for printing the info

    void print_c(ostream &cout) {

        cout << "Count : " << getCount() << "\n";

        cout << "Counter : " << getCounter() << "\n\n";

    }

};

// test method

int main(int argc, char const *argv[]) {

    int value;

    cout << "Please enter a COUNT value: ";

    cin >> value;

    CounterType c(value);

    // using while loop printing

    // count and counter

    while (1) {

        c.print_c(cout);

        c.increseCounter();

        int t = c.decreaseCount();

        // if count reach to 0 then nothing program will exit

        if (!t) {

            break;

        }

    }

    return 0;

}// end of program

Result Output:

0 0

Discussions

Post the discussion to improve the above solution.