Knowee
Questions
Features
Study Tools

Write a C++ Program to Show Counter using Constructor.input and output Current count: 0Current count: 3Current count: 1

Question

Write a C++ Program to Show Counter using Constructor.

Input and Output
Current count: 0
Current count: 3
Current count: 1

🧐 Not the exact question you are looking for?Go ask a question

Solution

Sure, here is a simple C++ program that uses a constructor to initialize a counter. The counter is then incremented and decremented to show the current count.

#include<iostream>
using namespace std;

class Counter {
    private:
        int count;
    public:
        // Constructor
        Counter() : count(0) {
            cout << "Current count: " << count << endl;
        }

        // Function to increment count
        void increment() {
            count++;
            cout << "Current count: " << count << endl;
        }

        // Function to decrement count
        void decrement() {
            count--;
            cout << "Current count: " << count << endl;
        }
};

int main() {
    Counter c;
    c.increment();
    c.increment();
    c.increment();
    c.decrement();
    return 0;
}

In this program, we have a class Counter with a private member variable count. The constructor Counter() initializes count to 0 and prints the current count. We also have two member functions increment() and decrement() to increase and decrease the count respectively, and print the current count after each operation.

In the main() function, we create an object c of the class Counter. This automatically calls the constructor, initializing the count to 0 and printing it. We then call increment() three times and decrement() once on c, each time printing the current count.

This problem has been solved

Similar Questions

Write a program to count number of words in a given string whose length is greater than 3.For example:Input Resultpython is easier than C3

Study the following program:i = 0while i < 3:       print(i)       i += 1 else:      print(0)  0 10 1 20 1 2 00 1 2 3

What’s wrong with the following code snippet?count = 0while count < 3:print(count)count -= 1

What will the following code print?counter = 1sum = 0while counter <= 6:    counter = counter + 2    sum = sum + counterprint(sum)

Compute the frequencycount of the following code fragment.for(i=0;i<n; i++)for(j=0;j<n; j++)printf(“%d”,a[i][j]);

1/1

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.