Challenge: Traffic Light
Completed
Use typedef enum { RED, GREEN, YELLOW } Light;. The light starts at RED, and every tick it changes RED → GREEN → YELLOW → RED. Read a number of ticks n and print the name of the light after each tick, one per line.
Input
One integer n (1 ≤ n ≤ 20).
Output
n lines with RED, GREEN or YELLOW.
Example
Input
4
Output
GREEN YELLOW RED GREEN
Editor
C
Hints
Each tick: work out the next light from the current one.
Then print its name with if/else or switch.
Solution explanation
The enum keeps track of the state, and each tick moves it to the next state in the cycle.
Show solution
#include <stdio.h>
typedef enum { RED, GREEN, YELLOW } Light;
int main() {
int n;
scanf("%d", &n);
Light now = RED;
for (int i = 0; i < n; i++) {
if (now == RED) {
now = GREEN;
} else if (now == GREEN) {
now = YELLOW;
} else {
now = RED;
}
if (now == RED) {
printf("RED\n");
} else if (now == GREEN) {
printf("GREEN\n");
} else {
printf("YELLOW\n");
}
}
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module