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: 0Current count: 3Current count: 1
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.
Similar Questions
What will be the output of the following C program?void count(int n){ static int d=1; printf(“%d “, n); printf(“%d “, d); d++; if(n>1) count(n-1); printf(“%d “, d); } void main(){ count(3); }a.3 1 2 1 1 1 2 2 2b.3 1 2 1 1 1 2c.3 1 2 2 1 3 4 4 4d.3 1 2 2 1 3 4
There is a strange counter. At the first second, it displays the number . Each second, the number displayed by decrements by until it reaches . In next second, the timer resets to and continues counting down. The diagram below shows the counter values for each time in the first three cycles:
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
What’s wrong with the following code snippet?count = 0while count < 3:print(count)count -= 1
void next( void ) { static int iteration =5; /* local static variable */ iteration ++; printf("iteration=%d and counter= %d\n", iteration, counter); }
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.