Answer to Question #187817 in C++ for Usama

Question #187817

Q1: Write a class named as Bus that contains the attributes which are mentioned below:

 The name of Bus.

 The direction of Bus (North (N), South(S), East(E), West (W))

 The position of Bus (from imaginary zero point)

The class has the following member functions:

 A constructor to initialize the attributes

 Turn function to change the direction of bus to one step right side (e.g if the direction is

to East, it should be changed to South and so on)

 Overload the Turn function to change the direction to any side directly. It should take the

direction as an argument.

 Move function to change the position of the Bus away from imaginary zero point. It

should accept the distance as an argument.



1
Expert's answer
2021-05-01T18:06:55-0400
#include <iostream>
#include <string>
 
using namespace std;
 
class Bus
{
public:
	Bus(string name_);
	void Turn(string direction);
	void Turn();
	void Move(int dist);
	void Display();
private:
	string name;
	int N;
	int S;
	int E;
	int W;
	string direct;
 
};
 
Bus::Bus(string name_) : N(0), S(0), E(0), W(0), name(name_), direct("N")
{
}
 
void Bus::Turn(string direction)
{
	if (direction == "S")
	{
		direct = "S";
		Move(1);
	}
	if (direction == "W")
	{
		direct = "W";
		Move(1);
	}
	if (direction == "E")
	{
		direct = "E";
		Move(1);
	}
	if (direction == "N")
	{
		direct = "N";
		Move(1);
	}
}
 
void Bus::Turn()
{
	if (direct == "S")
	{
		direct = "W";
		Move(1);
	}
	if (direct == "W")
	{
		direct = "N";
		Move(1);
	}
	if (direct == "E")
	{
		direct = "S";
		Move(1);
	}
	if (direct == "N")
	{
		direct = "E";
		Move(1);
	}
}
 
void Bus::Move(int dist)
{
	if (direct == "N")
	{
		if (N >= 0 && S == 0) N += dist;
		else if (dist <= S) S -= dist;
		else
		{
			N = dist - S;
			S = 0;
		}
	}
	if (direct == "S")
	{
		if (S >= 0 && N == 0) S += dist;
		else if (dist <= N) N -= dist;
		else
		{
			S = dist - N;
			N = 0;
		}
	}
	if (direct == "E")
	{
		if (E >= 0 && W == 0) E += dist;
		else if (dist <= W) W -= dist;
		else
		{
			E = dist - W;
			W = 0;
		}
	}
	if (direct == "W")
	{
		if (W >= 0 && E == 0) W += dist;
		else if (dist <= E) E -= dist;
		else
		{
			W = dist - E;
			E = 0;
		}
	}
}
 
void Bus::Display()
{
	cout << "Current position of " << name << " is: ";
	if (N != 0) cout << "North: " << N;
	if (S != 0) cout << "South: " << S;
	if (E != 0) cout << " East: " << E;
	if (W != 0) cout << " West: " << W;
	cout << endl;
}
 
 
 
int main()
{
	Bus bus("Billy");
	bus.Display();
	bus.Turn();
	bus.Move(10);
	bus.Display();
	bus.Turn("N");
	bus.Move(15);
	bus.Display();
	bus.Turn("S");
	bus.Move(50);
	bus.Display();
 
	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