0

Line Robot - Basic lessons - Switch

Using "if" command we learned earlier, we can perform all the branching in our program. However, sometimes "if" is not the best tool available. Consider this program:
void RobotLine::loop() {
	...
	if (someVariable == 1)
		print("1");
	else if (someVariable == 2)
		print("2");
	else if (someVariable == 3)
		print("3");
	else if (someVariable == 4)
		print("4");
	else if (someVariable == 5)
		print("5");
	else
		print("6");
	...
}
"..." is not a special command but it shows that some other code may go here, that is not in our focus of interest. someVariable is name of a variable that was defined somewhere in the first "..." part. There is no problem with this code fragment, only it can be written in another way, using switch command. The next code fragment will do exactly the same as the one above:
void RobotLine::loop() {
	...
	switch(someVariable){
		case 1:
			print("1");
			break;
		case 2:
			print("2");
			break;
		case 3:
			print("3");
			break;
		case 4:
			print("4");
			break;
		case 5:
			print("5");
			break;
		default:
			print("6");
	}
	...
}
No, it is not shorter, but it is more clear that all the "if" commands above check a common expression ("someVariable") and which values it is tested against. If You compare the 2 fragments, You will understand how the switch command should look like.

Task: states.

Write a program that executes loop() function 3 times. During the first pass it should write "dog", second "mouse", and third "cat".