The Basics of C++ on an Arduino, Part 4 Control Statements & Loops
2020-11-11 | By Maker.io Staff
This Basics of C++ on an Arduino series is covering many different elements necessary for all sorts of projects and ideas on an Arduino. In this entry, we cover control statements and loops.
The series so far has covered simple variables, arrays, and methods. However, there’s a little more to writing a program than these things. All the things you learned so far will allow you to store values and perform simple calculations; however, sometimes you have to make decisions in your program or repeat certain instructions multiple times. Therefore, it’s important to understand control statements and loops that’ll allow you to write more advanced programs.
Booleans and Conditions
Remember the booleans discussed in part one? These variables allow you to store a single boolean value - true or false. The Arduino can evaluate boolean expressions for you, and you can then instruct it to store the result in a variable:
// a will be false (5 is less than 2 -> false) boolean a = 5 < 2; // b will be true (10 equals 10 -> true) boolean b = 10 == 10; // c will be false // (10 not equals 2 -> true) AND (a equals b -> false) // true AND false -> false boolean c = (10 != 2) && ('a' == 'b'); // d will be true // true OR false -> true boolean d = true || false; // e will always be false // The exclamation mark negates a boolean expression // (not true) -> false boolean e = !true;
As you can see, it’s possible to compare different variables. However, you can also combine the results of these comparisons with the && (logical and) and || (logical or) operators. Furthermore, you can also invert the result of a boolean expression using an exclamation mark (logical not).
If-Else Statements
Now, take a look back at the blocks discussed in part two of this series. As mentioned, you can encapsulate certain statements inside a block. You can also add an if-statement to the beginning of a block to only execute the code inside of it if a certain condition is met:
float divide(float a, float b) { if(b > 0) { // Only executes the code in this block if b is greater than zero return a / b; } return 0; }
You can add an optional else-block right below an if-block, that only gets executed when the boolean expression evaluates to false:
float divide(float a, float b) { if(b > 0) { // Only executes the code in this block if b is greater than zero return a / b; } else { // Only executes the code in this block if b is less than zero return 0; } }
You can also chain multiple if- and else-if blocks together:
float divide(float a, float b) { if(b > 0 && a > 0) { // Only executes the code in this block if b is greater than zero return a / b; } else if(b <= 0 && a > 0) { // Only executes the code in this block if b is less than zero return 0; } else { // Do something else } return 0; }
Note that you can add as many else-if blocks as you want. However, you must always have an if-block; and you can only add at most one else-block.
Switch Statements
Switch statements represent a way of checking whether a variable has a specific value:
String getGreeting(int number) { switch(number) { // if (number == 0) -> return "Hello, " case 0: return "Hello, "; break; // else if (number == 1) -> return "Greetings, " case 1: return "Greetings, "; break; // else if (number == 2) -> return "Hi, " case 2: return "Hi, "; break; // else -> return "Dear, " default: return "Dear, "; } }
You could, of course, also use several chained if-else statements, as indicated by the comments. However, the switch statement usually increases the readability of your program when you want to perform such checks.
“While” Loops
Now you know how to check for conditions! However, what if you want to repeat the execution of a certain block multiple times? You could, of course, do the following to execute the block two times:
void setup() { int counter = 0; { readSensor(); counter = counter + 1; Serial.print("The sensor got read "); Serial.print(counter); Serial.println(" times!"); } { readSensor(); counter = counter + 1; Serial.print("The sensor got read "); Serial.print(counter); Serial.println(" times!"); } }
However, that is considered bad practice because it decreases the readability and maintainability of your code. Furthermore, what if you want to repeat this part 10 times, 100 times, or you don’t even know exactly how many times? This is where you can utilize loops. A while loop repeats the code inside a block as long as a certain condition is met:
while(counter <= 10) { readSensor(); counter = counter + 1; Serial.print("The sensor got read "); Serial.print(counter); Serial.println(" times!"); }
This will execute the block until the counter reaches a value of eleven. Note that you can use any boolean expression, just like with if-statements.
“For” Loops
If you want to execute a block a certain number of times, it’s often better to use a for loop instead of a while loop. This construct repeats a block a certain number of times, and it’ll also automatically increase the counter variable for you:
for(int counter = 0; counter <= 10; counter++) { readSensor(); Serial.print("The sensor got read "); Serial.print(counter); Serial.println(" times!"); }
In the head of the for loop, you define the counter variable and its starting value. You then specify a condition. The loop repeats itself as long as this condition holds. Lastly, you can specify what you want to happen to the variable after every iteration of the loop. In this example, the counter gets increased by one.
Note that you can use the counter variable inside of the loop. However, once you’ve reached the end of it, the variable becomes invalid.
The for and while loop can often get utilized exchangeably. You can, for example, also omit all the fields in the for loop to create an endless loop. It’s also possible to specify any condition or to omit single fields. Here are a few examples:
// You can use any boolean expression for(int counter = 0; 2 <= 5; counter++) { // Will run forever } // You can omit all the fields ... for(;;) { // Will run forever } // ... or just supply some of them for(;false;) { // Will never run } // You can initialize multiple variables and modify them // as you wish for(int x = 0, y = 200; x < y; x = x + 100) { // Will run two times } // You can also use other data-types for(char x = 'z'; x >= 'a'; x--) { // Answer this for yourself: // How many times will this run? What values will x have? // Now try it in the Arduino IDE! Were you correct? } // For loops are also perfect for accessing all elements of an array! int values[array_length] = { ... }; for(int i = 0; i < array_length; i++) { // Do something with the elements values[i] = values[i] * values[i]; Serial.println(values[i]); }
Recommended Reading
- The Basics of C++ on an Arduino, Part 1: Variables
- The Basics of C++ on an Arduino, Part 2: Functions and Methods
- The Basics of C++ on an Arduino, Part 3 Pointers and Arrays
- The Basics of C++ on an Arduino, Part 5: Software Libraries and Custom Classes
Summary
You can use many operators to build complex boolean expressions. These can then get utilized to execute some code segments only if a certain condition is met. You can use while- and for-loops interchangeably to repeat a certain block multiple times. These loops are especially useful when you want to go through all the elements in an array.
Have questions or comments? Continue the conversation on TechForum, DigiKey's online community and technical resource.
Visit TechForum