Implement a structure, Car. The structure has the following data member:
1. int petrolLevel – that indicates the liters of petrol in the car’s petrol tank. PetrolLevel for
this car can only be in the range 0 – 45 liters.
The structure has the following member functions:
1. void setPetrolLevel(int petrolLevelVal) – a setter for petrol level, cannot set value greater
than 45.
2. int getPetrolLevel() – a getter for petrolLevel
3. Car() – a default constructor
4. Car(int petrolLevelVal) – a parametrized constructor
5. bool MoveCar(int distanceKM) – a function that takes an integer as an argument and
moves the car to the argument value which is in Km. Provided the petrol tank has enough
fuel. Successful movement of the car returns true otherwise returns false. Moving for
each km causes the petrolLevel to go low by one.
6. void Refill() – a function that refills the car tank to the maximum value of petrolLevel
7. bool isEmpty() – a function that tells whether the Petrol tank is Empty or not
#include <iostream>
#include <iomanip>
using namespace std;
struct Car
{
int petrolLevel;
//a setter for petrol level, cannot set value greater than 45
void setPetrolLevel(int petrolLevelVal)
{
if (petrolLevelVal > 45)
petrolLevel = 45;
else
petrolLevel = petrolLevelVal;
}
//a getter for petrolLevel
int getPetrolLevel() { return petrolLevel;}
//a parametrized constructor
Car():petrolLevel(0){}
//a function that takes an integer as an argument and
//moves the car to the argument value which is in Km
bool MoveCar(int distanceKM)
{
if (distanceKM <= petrolLevel)
{
petrolLevel -= distanceKM;
return true;
}
else
return false;
}
//a function that refills the car tank to the maximum value of petrolLevel
void Refill()
{
petrolLevel = 45;
}
// a function that tells whether the Petrol tank is Empty or not
bool isEmpty()
{
if (petrolLevel == 0)
return true;
else
return false;
}
};
int main()
{
Car a;
cout << "Make Car object before the filling car tank:\n";
cout << "a.getPetrolLevel() = " << a.getPetrolLevel();
cout << "\na.isEmpty() = " <<boolalpha<< a.isEmpty();
cout << "\na.MoveCar(10) = "<< boolalpha << a.MoveCar(10);
cout << "\nFill car tank on 20:";
a.setPetrolLevel(20);
cout << "\na.getPetrolLevel() = " << a.getPetrolLevel();
cout << "\na.isEmpty() = " << boolalpha << a.isEmpty();
cout << "\na.MoveCar(10) = " << boolalpha << a.MoveCar(10);
cout << "\na.getPetrolLevel() = " << a.getPetrolLevel();
cout << "\nRefill the car tank to the maximum:";
a.Refill();
cout << "\na.getPetrolLevel() = " << a.getPetrolLevel();
}
Comments
Leave a comment