Soccer Robot C - Basic lessons - || and &&
We learned how to stop a robot when one transistor spots a white surface. Now suppose we want it to stop if
any of the transistors of the left reflectance sensor senses white. There is a clumsy way to achieve the goal and here it is (don't do this!):
void RobotSoccer::loop() {
if (setup())
go(50, 0);
if (line(0, 1))
stop();
else if (line(1, 1))
stop();
else if (line(2, 1))
stop();
else if (line(3, 1))
stop();
else if (line(4, 1))
stop();
else if (line(5, 1))
stop();
else if (line(6, 1))
stop();
else if (line(7, 1))
stop();
}
Yes, You can nest if-commands like above, but the point is that the code is long and difficult to understand. We are lucky that C++ (like other languages) has
or logical operator. Its format is:
logicalExpression1 || logicalExpression2
The "||" is the or-operator. The meaning is: if any of the logical expressions logicalExpression1 or logicalExpression2 is true, the whole expression is true. That's natural. Look at the example:
if (6 < 2 || 6 < 9)
print("Yes");
Will the code fragment print "Yes" or not? Of course it will. 6 < 2 is not true, but 6 < 9 is. Therefore, as at least one of the expressions is true, the whole expression is true. This logic is natural.
Besides "or", the other logical operator is "and", in C++ notation "&&". The whole expression takes this form:
logicalExpression1 && logicalExpression2
The result is "true" only if both logicalExpression1 and logicalExpression2 are "true". Otherwise is "false". A few expressions that evaluate as "true":
- 1 < 2 && 2 < 3
- 1 < 2 && 1 < 2
Now some that evaluate as "false":
- 1 < 2 && 2 < 1
- 2 < 1 && 2 < 1
Task: stop if any sensor detects a white line.
Write a program that will stop the robot if any transistor encounters a white line.
Solution
void RobotSoccer::loop() {
if (line(0, 1) || line(1, 1) || line(2, 1) || line(3, 1) || line(4, 1) || line(5, 1) || line(6, 1) || line(7, 1))
stop();
else
go(50, 0);
}