We define a Lift class that has private member variables currentFloor to
keep track of the current floor and isMoving to indicate if the lift is in motion.
The Lift class also has a public member function moveToFloor that takes an integer
parameter floor. This function checks if the specified floor is valid and if the lift is
already in motion or already on the desired floor. If everything is valid, it simulates
the lift moving from the current floor to the desired floor by updating the currentFloor
variable and displaying the progress.
In the main function, we create a Lift object and call the moveToFloor function with
different floor numbers to simulate the lift's movement.
#include<bits/stdc++.h>
#include<iostream>
#include<cmath>
class Lift {
private:
int currentFloor;
int totalFloors;
public:
Lift(int floors) : currentFloor(1), totalFloors(floors) {}
void moveToFloor(int floor) {
if (floor < 1 || floor > totalFloors) {
std::cout << "Invalid floor. Lift cannot go to this floor.\n";
} else {
std::cout << "Moving from floor " << currentFloor << " to floor " << floor << ".\n";
currentFloor = floor;
}
}
void requestFloor() {
int floor;
std::cout << "Enter the floor number to go to: ";
std::cin >> floor;
moveToFloor(floor);
}
int getCurrentFloor() const {
return currentFloor;
}
int getTotalFloors() const {
return totalFloors;
}
};
int main() {
int totalFloors;
std::cout << "Enter the total number of floors in the building: ";
std::cin >> totalFloors;
Lift lift(totalFloors);
std::cout << "Lift created with " << totalFloors << " floors.\n";
while (true) {
int option;
std::cout << "Current floor: " << lift.getCurrentFloor() << "\n";
std::cout << "Options:\n";
std::cout << "1. Request a floor\n";
std::cout << "2. Exit\n";
std::cout << "Enter your choice: ";
std::cin >> option;
if (option == 1) {
lift.requestFloor();
} else if (option == 2) {
std::cout << "Exiting the lift system.\n";
break;
} else {
std::cout << "Invalid option. Please try again.\n";
}
}
return 0;
}