KevsRobots Learning Platform
40% Percent Complete
By Kevin McAleer, 3 Minutes
Page last updated June 15, 2025
Now that you can store data with variables, letβs add logic to your programs with conditionals and loops.
This lesson will teach your programs how to make decisions and do things over and over again β two key skills for any kind of automation or embedded programming.
Use if
to check if something is true, and act accordingly.
#include <stdio.h>
int main() {
int temperature = 30; // Set the variable temperature to 30
if (temperature > 25) { // Check if temperature is greater than 25
printf("It's hot today!\n");
} else { // If not, do this
printf("It's not too hot.\n");
}
return 0; // End the program
}
You can also use else if
:
if (temp > 25) {
// ...
} else if (temp > 15) {
// ...
} else {
// ...
}
Operator | Meaning | Example |
---|---|---|
== |
Equal to | a == b |
!= |
Not equal to | a != b |
> |
Greater than | a > b |
< |
Less than | a < b |
>= |
Greater or equal | a >= b |
<= |
Less or equal | a <= b |
Loops let you repeat something multiple times β great for blinking LEDs, checking sensors, or running forever.
while
Loopint count = 0;
while (count < 5) { // Repeat the code block while count is less than 5
printf("Count: %d\n", count);
count++; // Increment count by 1
}
This will print Count: 0
through Count: 4
.
for
LoopA for
loop is a shorter way to repeat something a specific number of times. for loops require three parts:
int i = 0;
this sets the starting value of the loop variable i
.i < 5;
this checks if i
is less than 5, when the value of i
reaches 5, the loop stops.i++
this increases the value of i
by 1 each time the loop runs.for (int i = 0; i < 5; i++) {
printf("i = %d\n", i);
}
This does the same thing as the while loop above β itβs just shorter.
Microcontrollers often run in an infinite loop, doing tasks over and over:
while (1) {
// Do something forever
}
Weβll use this when we get to controlling the LED!
You now know how to:
if
, else if
, and else
while
and for
loopsNext up: Functions in C, where weβll start breaking our programs into reusable chunks!
You can use the arrows β β
on your keyboard to navigate between lessons.