Imagine a tollbooth at a bridge. Cars passing by the booth are expected to pay a
ID: 3568138 • Letter: I
Question
Imagine a tollbooth at a bridge. Cars passing by the booth are expected to pay a 50 pesewas toll. Mostly they do, but sometimes a car goes by without paying. The tollbooth keeps track of the number of cars that have gone by, and of the total amount of money collected.
Model this tollbooth with a class called tollBooth. The two data items are a type unsigned int to hold the total number of cars, and a type double to hold the total amount of money collected. A constructor initializes both of these to 0.
A member function called payingCar() increments the car total and adds 0.50 to the cash total.
Another function, called nopayCar(), increments the car total but adds nothing to the cash total.
Finally, a member function called display() displays the two totals. Make appropriate member functions const.
Include a program to test this class. This program should allow the user to push one key to count a paying car, and another to count a nonpaying car. Pushing the Esc key should cause the program to print out the total cars and total cash and then exit.
Here is my code...
#include<iostream>
using namepace std;
int main()
{
tollbooth b1;
char ch;
do
{
cout << "P - Paid N - Not Paid Q - Quit -> ";
cin >> ch;
switch (ch=tolower(ch))
{
case 'p':
b1.Payincar();
break;
case 'n':
b1.nopaycar();
break;
}
}
While (ch != 'q');
b1.display(cout);
return(0);
}
Explanation / Answer
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
class tollbooth
{
int no_of_car;
int tot_toll;
public:
tollbooth()
{
no_of_car = 0;
tot_toll = 0;
}
void car_passes();
void paying_car(void);
void non_paying_car(void);
void display(void);
};
void tollbooth :: car_passes()
{
char cartype;
cout<<" Enter Car Type Paying car(P) & Nonpaying car(N) : ";
cin>>cartype;
if(cartype=='P'||cartype=='p')
paying_car();
else if(cartype=='N'||cartype=='n')
non_paying_car();
}
void tollbooth :: paying_car(void)
{
tot_toll=tot_toll+50;
no_of_car=no_of_car+1;
}
void tollbooth :: non_paying_car(void)
{
no_of_car=no_of_car+1;
}
void tollbooth :: display()
{
cout<<" Total number of cars passed :"<<no_of_car;
cout<<" Total amount collected :"<<tot_toll;
}
int main()
{
tollbooth t;
int ch;
clrscr();
cout<<" Menu";
cout<<" 1. Car Passes";
cout<<" 2. Display";
cout<<" 3. Exit";
cout<<" Enter your choice";
cin>>ch;
switch(ch)
{
case 1: t.car_passes();
break;
case 2: t.display();
break;
case 3:exit(0);
}
getch();
return 0;
}