Conditional Statement syntax in C
If Statement
Format
If
c
if (condition) {
// run task when meet condition
}if else
c
if (condition) {
// run task when meet condition
} else {
// run when task not meet condition
}if else-if else
c
if (condition) {
// run task when meet condition
} else if (condition2){
// run when task meet condition2
} else {
// run when task not meet condition and condition2
}Switch Statement
Format
c
switch (variable) {
case value1:
// run task when variable = value1
break;
case value2:
// run task when variable = value2
break;
default:
// run fallback task
// when all the value is not equal to variable
break;
}For Statement
- for statement is a loop / repeat statement
Format
c
for (initial Value Expression; bool Expression; update State Expression;) {
// code
}initial Value Expression;defines a initial value of a looping variablebool Expression;are usually Comparision statement (>, <, ==, ...)update State Expression;updates the value of looping variable, so the value will slowly approached and meet the conditon
Example
c
for (i = 0; i < 10; i ++;) {
// print 0 - 9
Serial.println(i);
}While Statement
- The variable in loop of while will put outside the while loop block.
- Inside the while loop block will handling the variable change
Format
c
while (bool expression) {
// code
}Example
c
int i = 0;
while (i < 10) {
Serial.println(i);
i++;
}