In: Computer Science
Write a class Car that contains the following attributes:
Below is your program
#include <string.h>
#include <iostream>
using namespace std;
class car
{
int pos;
char car_name[20];
char dir;
public:
void turn();
void move(int);
void turn(char);
car(char name[], char d, int p)
{
strcpy(car_name,name);
dir=d;
pos=p;
}
void display() {
cout<<"\nCar Name: "<<car_name<<", Position: "<<pos<<", Direction: "<<dir<<endl;
}
};
void car :: turn()
{
switch(dir)
{
case 'N' : dir='E';
break;
case 'E' : dir='S';
break;
case 'S' : dir='W';
break;
case 'W' : dir='N';
break;
default : cout<<"THE DIRECTION IS INCORRECT !!!";
}
}
void car :: turn(char d1)
{
dir=d1;
}
void car :: move(int p1)
{
pos+=p1;
}
int main()
{
class car c("NANO",'N',100);
char ch;
char dir;
int p1,ch1;
c.display();
bool done = false;
while(!done)
{
cout<<"\n1.change in direction sequntially";
cout<<"\n2.change in direction randomly";
cout<<"\n3.change in position of the car";
cout<<"\n4.Exit";
cout<<"\nEnter your choice\n";
cin>>ch1;
switch(ch1)
{
case 1:
c.turn();
break;
case 2:
cout<<"input the required direction\n ";
cin>>dir;
c.turn(dir);
break;
case 3:
cout<<"\nEnter the require position\n";
cin>>p1;
c.move(p1);
break;
case 4:
done = true;
break;
default:
cout<<"\nWrong choice";
}
cout<<"Car Details: "<<endl;
c.display();
}
return 0;
}
Output
Car Name: NANO, Position: 100, Direction: N
1.change in direction sequntially
2.change in direction randomly
3.change in position of the car
4.Exit
Enter your choice
1
Car Details:
Car Name: NANO, Position: 100, Direction: E
1.change in direction sequntially
2.change in direction randomly
3.change in position of the car
4.Exit
Enter your choice
1
Car Details:
Car Name: NANO, Position: 100, Direction: S
1.change in direction sequntially
2.change in direction randomly
3.change in position of the car
4.Exit
Enter your choice
1
Car Details:
Car Name: NANO, Position: 100, Direction: W
1.change in direction sequntially
2.change in direction randomly
3.change in position of the car
4.Exit
Enter your choice
2
input the required direction
N
Car Details:
Car Name: NANO, Position: 100, Direction: N
1.change in direction sequntially
2.change in direction randomly
3.change in position of the car
4.Exit
Enter your choice
1
Car Details:
Car Name: NANO, Position: 100, Direction: E
1.change in direction sequntially
2.change in direction randomly
3.change in position of the car
4.Exit
Enter your choice
3
Enter the require position
50
Car Details:
Car Name: NANO, Position: 150, Direction: E
1.change in direction sequntially
2.change in direction randomly
3.change in position of the car
4.Exit
Enter your choice
1
Car Details:
Car Name: NANO, Position: 150, Direction: S
1.change in direction sequntially
2.change in direction randomly
3.change in position of the car
4.Exit
Enter your choice
4
--------------------------------
Process exited after 26.09 seconds with return value 0
Press any key to continue . . .