Answer to Question #326777 in C++ for ItsmeZee

Question #326777

Create a counter class, overload ++ operator for counter post and pre increment, use the

object of counter class as a loop counter for printing a table in main function.


1
Expert's answer
2022-04-10T17:45:11-0400
#include <iostream>
#include <iomanip>
using namespace std;


class Counter {
    int value;
public:
    Counter(int v=0) : value(v) {}
    Counter& operator++();          // Prefix
    Counter operator++(int);        // Postfix
    int getValue() const {
        return value;
    }    
};



Counter& Counter::operator++() {
    value++;
    return *this;
}


Counter Counter::operator++(int) {
    Counter tmp = *this;
    value++;
    return *this;
}


int main() {
    cout << " x | x^2" << endl;
    for (Counter c(1); c.getValue()<=10; ++c) {
        int x = c.getValue();
        cout << setw(2) << x << " | " << setw(3) << x*x << endl;
    }
    return 0;
}

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