Traffic Light
Programming Basics · C++
TASK
Problem
Given an integer traffic-light code: 1 = red, 2 = yellow, 3 = green. Print the corresponding English color name.
EXAMPLE
Example
1
red
LIMITS
Constraints
1 ≤ code ≤ 3.
LEARN
Theory for this problem
+
An `if` / `else if` / `else` chain checks alternatives from top to bottom. Put more specific or higher-priority conditions first.
Connection to “Traffic Light”: here, branching selects a case using a Boolean condition; test order matters when cases overlap.
NEED HELP?
Hints
+
['List the possible cases and make them mutually exclusive.', 'After solving “Traffic Light”, verify the algorithm on your own small example and on an allowed boundary case. Print only the required result with no extra text.']
ANSWER
Solution
+
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
long long n;
cin >> n;
if (n == 1) cout << "red";
else if (n == 2) cout << "yellow";
else cout << "green";
cout << '\n';
return 0;
}