106k views
1 vote
Write a C++ Program:

Write a class Bug that models a bug moving along a horizontal line. The bug moves either to the right or left. Initially, the bug moves to the right, but it can turn to flip its direction (if the current direction is right, turn to left; if the current direction is left, turn to right). In each move, its position changes by one unit in the current direction.
Provide a constructor
Bug(int initial_position)
and member functions
void turn()
void move()
int get_position() const
Sample usage:
Bug bugsy(10);
bugsy.move(); // Now the position is 11
bugsy.turn();
bugsy.move(); // Now the position is 10

Thank you!

User Soteria
by
7.9k points

1 Answer

5 votes

Answer:

Here is the C++ program that meets the given requirements:

```

#include <iostream>

using namespace std;

class Bug {

public:

Bug(int initial_position);

void turn();

void move();

int get_position() const;

private:

int position;

int direction;

};

Bug::Bug(int initial_position) {

position = initial_position;

direction = 1;

}

void Bug::turn() {

direction = -direction;

}

void Bug::move() {

position += direction;

}

int Bug::get_position() const {

return position;

}

int main() {

Bug bugsy(10);

bugsy.move();

cout << bugsy.get_position() << endl;

bugsy.turn();

bugsy.move();

cout << bugsy.get_position() << endl;

return 0;

}

```

Here is how the program works:

1. The program defines a class Bug with a constructor that takes an initial position and sets the current direction to right (represented by 1) and a member function turn() that changes the direction of the bug.

2. The program also defines member functions move() that moves the bug one unit in the current direction and get_position() that returns the current position of the bug.

3. In the main function, a Bug object bugsy is created with an initial position of 10.

4. The bugsy object is then moved one unit to the right using the move() function and its position is printed to the console.

5. The turn() function is called to change the direction of the bug.

6. The bugsy object is moved one unit in the new direction using the move() function and its position is printed to the console.

Note that the direction of the bug is represented by an integer value of either 1 (right) or -1 (left). When the turn() function is called, the direction is changed by multiplying the current direction by -1. This flips the direction from right to left or from left to right.

User Seb Jachec
by
8.2k points

No related questions found