Write a C++ program for Traffic Light Simulation: Red, Yellow, Green.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | #include <iostream> using namespace std; int main() { int option; int lightState = 1; // 1 for Red, 2 for Yellow, 3 for Green while (true) { // Display the menu cout << "Traffic Light Simulation Menu:\n"; cout << "1. Show Current Light\n"; cout << "2. Change Light\n"; cout << "3. Exit\n"; cout << "Enter your option (1-3): "; cin >> option; // Handle the user's choice switch (option) { case 1: // Show current light switch (lightState) { case 1: cout << "Current light is Red\n"; break; case 2: cout << "Current light is Yellow\n"; break; case 3: cout << "Current light is Green\n"; break; default: cout << "Unknown light state\n"; break; } break; case 2: // Change light switch (lightState) { case 1: lightState = 2; // Change from Red to Yellow cout << "Changing light to Yellow\n"; break; case 2: lightState = 3; // Change from Yellow to Green cout << "Changing light to Green\n"; break; case 3: lightState = 1; // Change from Green to Red cout << "Changing light to Red\n"; break; default: cout << "Unknown light state\n"; break; } break; case 3: // Exit cout << "Exiting the traffic light simulation. Thank you!" << endl; return 0; // Exit the program default: // Invalid option cout << "Invalid option. Please enter a number between 1 and 3." << endl; break; } } return 0; } |
Possible Outputs
Output#1
Traffic Light Simulation Menu:
1. Show Current Light
2. Change Light
3. Exit
Enter your option (1-3): 1
Current light is Red
Output#2
Traffic Light Simulation Menu:
1. Show Current Light
2. Change Light
3. Exit
Enter your option (1-3): 2
Changing light to Yellow
Output#3
Traffic Light Simulation Menu:
1. Show Current Light
2. Change Light
3. Exit
Enter your option (1-3): 1
Current light is Yellow
Output#4
Traffic Light Simulation Menu:
1. Show Current Light
2. Change Light
3. Exit
Enter your option (1-3): 2
Changing light to Green
Output#5
Traffic Light Simulation Menu:
1. Show Current Light
2. Change Light
3. Exit
Enter your option (1-3): 1
Current light is Green
Output#6
Traffic Light Simulation Menu:
1. Show Current Light
2. Change Light
3. Exit
Enter your option (1-3): 2
Changing light to Red
Output#7
Traffic Light Simulation Menu:
1. Show Current Light
2. Change Light
3. Exit
Enter your option (1-3): 3
Exiting the traffic light simulation. Thank you!