Increment Operator
The increment operator is an Arduino arithmetic operator that increments an integer variable by a value of one. This is useful in certain types of loops.
Two possible structures of increment operator:
- Variable_Name++: As the ‘++’ sign is after the variable name, it is a post-increment operation. This means that the variable is first used in the statement and incremented after the statement execution.
- ++Variable_Name: As the ‘++’ sign is before the variable name, it is a pre-increment operation. This means that the variable is incremented before the execution of the statement.
Example showing the working of the post-increment operation:
int count = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.print("Count Value: ");
Serial.println(count++);
delay(1000);
}
Example showing the working of the pre-increment operation:
int count = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.print("Count Value: ");
Serial.println(++count);
delay(1000);
}
Decrement Operator
The decrement operator is used to decrement an integer variable by a value of one.
Two possible structures of increment operator:
- Variable_Name – -: As the ‘–‘ sign is after the variable name, it is a post-decrement operation. This means that the variable is first used in the statement and decremented after the statement execution.
- – – Variable_Name: As the ‘–‘ sign is before the variable name, it is a pre-decrement operation. This means that the variable is decremented before the execution of the statement.
Example of post-decrement operation:
int count = 100;
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.print("Count Value: ");
Serial.println(count--);
delay(1000);
}
Example of pre-decrement operation:
int count = 100;
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.print("Count Value: ");
Serial.println(--count);
delay(1000);
}
Conclusion
In this lesson, we discussed the increment and decrement operators and their structures. We also looked at examples of how to use these operators in Arduino programs. Increment and decrement operators are useful tools for controlling the flow of a program, and understanding how to use them is an important part of mastering the Arduino programming language.