Sub topic 2
Constants, Operators, Decisions, Loops, and Arrays
This chapter assumes you can write a basic sketch with setup() and loop(), and that you know how pinMode() and digitalWrite() drive an LED.
Constants with const and #define
A constant is a value that cannot change after the program starts. Use const for typed constants, which the compiler checks. Use #define for simple text substitution, which the preprocessor performs before compiling.
const int ledPin = 13; // typed constant, checked by the compiler
#define BLINK_MS 500 // replaced by 500 before compiling
const int readings[] = {3, 7, 1, 9};
const int count = sizeof(readings) / sizeof(readings[0]);
void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
int total = 0;
for (int i = 0; i < count; i++) {
total += readings[i];
}
Serial.println(total);
digitalWrite(ledPin, (total > 15) ? HIGH : LOW);
delay(BLINK_MS);
}Operators and expressions
An expression combines values with operators. Arithmetic operators include +, -, *, /, and % (remainder). Comparison operators such as ==, !=, <, and > produce true or false. Logical operators && (and), || (or), and ! (not) combine those results.
Making decisions with if, else, and switch
if runs a block only when its condition is true. switch picks one case from a single value. Each case needs a break, or execution falls through into the next case.
int mode = 2;
if (mode == 1) {
Serial.println("Slow");
} else if (mode == 2) {
Serial.println("Medium");
} else {
Serial.println("Fast");
}
switch (mode) {
case 1:
Serial.println("Slow");
break;
case 2:
Serial.println("Medium");
break;
default:
Serial.println("Fast");
}Repeating work with for, while, and do-while
| Loop type | Condition checked | Typical use |
|---|---|---|
| `for` | Before each pass | Counting with a known range |
| `while` | Before each pass | Repeating until a state changes |
| `do-while` | After each pass | Running at least once |
Arrays and looping over them
An array stores several values of one type under one name. Indexes start at 0 and end at length - 1. The for loop in the first example reads each element in turn.
Exercise
The loop in the first example uses i < count. What goes wrong if you change it to i <= count?
Show answer
The loop runs one extra time and reads readings[4], which does not exist for an array of four elements. The result is undefined behavior.