Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Implement a counter ADT using a struct and four functions. A counter is a simple

ID: 3731219 • Letter: I

Question

Implement a counter ADT using a struct and four functions. A counter is a simple device we can use to count up from zero. Think of the clickers that are used to count the number of people that pass a door or who are in an audience. The struct should contain a string for a counter's name, and a number for the value. Create four functions: create_counter (creates a counter based on a name, initializes the count, and returns it), increment (takes a counter and increases it value by one), tally (returns the value of a counter), and display (prints out the counter with the format "NAME shows VALUE."). The specific syntax for these functions is shown indirectly at the bottom of the page - there is sample code that uses the counter ADT and the output of running it.

//a struct to contain counter information

struct counter {

       //function to create counters

       //function to increment a counter

       //function to get a counter's tally

       //function to display a counter's tally

       //SAMPLE USAGE

       void main() {

              struct counter c1 = create_counter("First");

              struct counter c2 = c1;

              increment(&c1);

              increment(&c2);

              display(&c1);  //output: First shows 1.

              display(&c2);  //output: First shows 1.

       }

Explanation / Answer

#include <iostream>
using namespace std;


//a struct to contain counter information
struct counter {
            string name;
            int value;
};





       //function to create counters

struct counter create_counter(string name)
{
struct counter c;
c.name = name;
c.value = 0;
return c;
}






       //function to increment a counter

     void increment(struct counter *c)
     {
     c->value++;
     }



       //function to get a counter's tally

    int tally(struct counter c)
    {
    return c.value;
    }



       //function to display a counter's tally
    void display(struct counter *c)
    {
    cout<<" "<<c->name<<" shows : "<<c->value;
    }





       //SAMPLE USAGE
       int main() {
              struct counter c1 = create_counter("First");
              struct counter c2 = c1;
              increment(&c1);
              increment(&c2);
              display(&c1); //output: First shows 1.
              display(&c2); //output: First shows 1.
              return 0;
       }

output:

First shows : 1
First shows : 1

Do ask if any query. Please upvote if the answer is helpful.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote