Answer to Question #183031 in C++ for Vincenzo Santoro

Question #183031

Define a class counterType to implement a counter. Your class must have a private data member counter of type int. Define a constructor that accepts a parameter of type int and initializes the counter data member. Add functions to:

  • Set counter to the integer value specified by the user.
  • Initialize counter to 0.
  • Return the value of counter with a function named getCounter.
  • Increment and decrement counter by one.
  • Print the value of counter using the print function.
  • Example output: Counter = 0.

The value of counter must be nonnegative.


1
Expert's answer
2021-05-04T05:23:24-0400
#include<iostream>
#include <stdio.h>
#include <string>
using namespace std;


class counterType{
	int counter;
	
	public:
	counterType(int count)
	{
		counter = count;	
	}
	
	void setCounter(int c)
	{
		counter = c;
	}
	
	int getCounter()
	{
		return counter;
	}
	
	int increment()
	{
		return ++counter;
	}
	
	int decrement()
	{
		if(counter < 0)
		{
			cout<<endl;
			cout<<"Value of counter is negative "<<endl;
			return counter;
		}
		return --counter;
	}
	
	void print()
	{
		cout<<"Final value of Counter : "<<counter<<endl;
	}
};


int main()
{
	counterType obj1(10);
	int c;
	cout<<"Enter the value of counter (>0) : "<<endl;
	cin>>c;
	obj1.setCounter(c);
	cout<<"Value of counter initially : "<<obj1.getCounter()<<endl;
	cout<<"Value of counter after Incrementing : "<<obj1.increment()<<endl;
	cout<<"Value of counter after Decrementing : "<<obj1.decrement()<<endl;
	cout<<endl;
	
	obj1.print();
	
}




Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS