0

Line Robot - Basic lessons - Branching

As we stated before, function loop() loops continually. Doing the same job in every pass wouldn't be very useful. In order to address this issue, most of the programs feature branching, a part of the program - a command - that can direct the program flow in 2 or more different "branches". Many languages use word "if" for this command, and C++ does the same. Look at the simple branching:
void RobotLine::loop() {
	if (1<2)
		print("Yes");
	else
		print("No");
}
if command has the following form:
if (logicaExpression)
	commandForTrue;
else
	commandForNotTrue;
Look at the program again. What is the logical expression there? Right, "1<2". Logical expressions always evaluate as "true" or "false". In our example 1 really is less than 2, therefore the logical expression evaluates as "true". If so, the first command after "if" is executed. In our case, "Yes" will be printed. You may notice that the example is rather stupid because the program will never print "No". The cause is that the logical expression is constant, never changes. However, later we will encounter much more interesting logical expressions, which are not constant.
To test if the 2 sides of a logical expression are the same, use equality operator: "==", which has a meaning of common "=" in mathematics. These statements are true "2 == 2", "7 == 7". Of course, the following one isn't: "3 == 7". So,
void RobotLine::loop() {
	if (1==2)
		print("Yes");
	else
		print("No");
}
will print "No". Remember that the operator is "==" and You cannot write it as "=". The command
if (1=2)
will result in an error. Every C++ programmer did that mistake, some hundreds of times. We will learn later what "=" stands for.

Task: write "No"

Change the program above so that it prints "No". You can change only one character.