current_state to hold the current stateswitch-case statement to handle state transitionscurrent_state to hold the current stateswitch-case statement to handle state transitionsenum called TrafficLight with the states RED, GREEN, and YELLOW. Then create a variable called current_state of type enum TrafficLight and set it to RED.Use enum TrafficLight { RED, GREEN, YELLOW }; to define the states and then enum TrafficLight current_state = RED; to set the initial state.
int variable called timer and set it to 0. This will count seconds in each state.Just add int timer = 0; below the current_state variable.
switch statement on current_state. For each case (RED, GREEN, YELLOW), print the state name using printf. Then update current_state to the next state in this order: RED -> GREEN -> YELLOW -> RED.Use switch (current_state) and inside each case, print the state name and update current_state to the next state.
printf statement after the switch-case block to print the text "Current state updated.".Use printf("Current state updated.\n"); after the switch-case block.
What is the main purpose of using a switch-case statement in a simple state machine?
Which of the following is the correct syntax for a switch statement in embedded C?
switch(state) {
case 0:
// code
break;
case 1:
// code
break;
default:
// code
}What will be the output of this code snippet?
int state = 1;
switch(state) {
case 0:
printf("State is zero\n");
break;
case 1:
printf("State is one\n");
break;
default:
printf("Unknown state\n");
}Find the error in this state machine code snippet:
int state = 0;
switch(state) {
case 0:
printf("Start\n");
case 1:
printf("Running\n");
break;
default:
printf("Unknown\n");
}You want to design a simple state machine with three states: INIT (0), PROCESS (1), and DONE (2). The machine should start at INIT, then move to PROCESS, and finally to DONE. Which code snippet correctly updates the state inside the switch-case?
int state = 0;
switch(state) {
case 0:
// Move to PROCESS
state = 1;
break;
case 1:
// Move to DONE
state = 2;
break;
case 2:
// Finished
break;
}Pass the test and this pattern moves unknown