
Welcome to the 4th installment of the C Programming Tutorials!
This time around, we’re going to talk about some common C control structures and conditional statements.
These let you do some amazing things with a little amount of code.
Normally, statements in a program execute one after the other in the order in which they appear. The word for this is sequential execution. The statements we will cover here enable the programmer to specify that the next line to execute may be other than the next one in sequence.
In other words, instead of executing statements in order, control structures will allow us to jump to other places in the program. This is a very powerful concept as we’ll soon see.
We’ll start with a quick intro to pseudocode and then jump into the if statement.
Pseudocode
Pseudocode is an artificial, informal language that helps programmers develop algorithms.
It’s kind of like real code, but also close to every day English. Pseudocode is convenient and user friendly. It leaves out some of the details the processor or microcontroller would need, so it’s not an actual computer programming language. However, pseudocode is more human-readable and is a good starting point when writing complex programs in any language.
And a carefully written pseudocode “program” can easily be converted into C.
Below is an example of pseudocode that tells you if you’ve passed a test.
If your grade is greater than or equal to 60% Print “ You Passed.” else Print “You Failed.”
One advantage of pseudocode is that it enables you to concentrate on the logic and organization of a program and spares you from simultaneously worrying about how to express the ideas in a computer language. And it’s not tied to any particular language.
I know this seems sort of random, but since control structures allow you to write more complex C programs, now is a good time to introduce the concept of pseudocode.
Now let’s delve into some common C programming control structures.
C Programming Control Structures
C Programming: the if Statement
The if statement checks for a condition and executes the proceeding statement or set of statements if the condition is true. If false, it skips the statement.
The if statement is called a branching statement or selection statement because it provides a junction where the program selects which of two paths to follow.
The syntax for an if statement is simple and goes something like this:
if (condition) { //Do some stuff }
For example, let’s say you want to turn on a fan when the attic hits a certain temperature.
To read the temperature, a thermistor (heat sensitive resistor) connects to a microcontroller’s ADC.
Let’s assume a 10-bit ADC. The values the ADC will return will range from 0 to 1023. So, if it’s cold, the value with be on the small side and if it’s hot the value will be larger.
Become the Maker you were born to be. Try Arduino Academy for FREE!
Let’s look at an if statement that could accomplish this in pseudocode.
Declare an integer and set it equal to what readADC returns If readADC returns a value greater than 500 (which means it’s hot) Execute code to run the fan
This pseudocode snippet reads the ADC with readADC (which is a function, we’ll talk more about functions in another tutorial) and then assigns that value to an integer named Temp.
As we can see below, translating the pseudocode into more realistic code isn’t difficult.
int Temp = readADC(); if (Temp > 500) { // code to run the fan goes here }
Note that the code inside the curly braces only executes if the conditional statement is true. If readADC() returns a value less than 500, the code does not execute.
An if…else statement is a power-up for your if statements. It allows you greater control over the flow of code than the basic if statement. This will allow you to test for more than one condition.
For example:
if (Temp > 500) { //code to turn on fan goes here } else if (Temp < 300) { //code to sound an alarm goes here }
Here we turn on the fan if it’s too hot as before, but now if it gets too cold we sound an alarm. Note that we can use as many else…if statements as we like to test for as many conditions as we want.
C Programming: the for Loop
The for loop is one of the most useful and common pieces of code out there. It’s often used with arrays, a subject that you’ll want to become familiar with which we’ll cover in a future tutorial. The syntax is shown below.
for (initialization; condition; incrementation) { //code goes here… }
The parentheses following the keyword for contain three expressions separated by two semicolons.
The first expression is the initialization. It happens just once, when the loop first starts.
The second expression is the test condition; it is evaluated before each potential execution of a loop. When the expression is false, the loop terminates.
The third expression, the incrementation, is evaluated at the end of each loop.
At first, the for loop can be confusing and intimidating, but after a while you’ll become good friends.
An example from the Arduino website is given here. The for loop in Arduino works the same way as in C and the syntax is the same. Remember that in Arduino main() is hidden and setup() and loop() are required.
// Dim an LED using a PWM pin int PWMpin = 10; // LED in series with 470 ohm resistor on pin 10 void setup() { // no setup needed } void loop() { for (int i=0; i <= 255; i++){ analogWrite(PWMpin, i); delay(10); } }
Take a look at the for loop. First, we set or initialize the variable i to 0 (this part only happens once the first time we go through the loop; after the first time this statement is ignored and the other two are executed).
Then comes the condition. As long as i is less than or equal to 255 we run through the loop. Integer i starts at 0, which is less than 255, so we step into the loop and write the value of i to PWMpin.
Then we increment i (the i++ statement increments it by one each time it passes through the loop). Once i becomes greater than 255, we fall out of the loop and the code inside the loop ceases to execute.
The for loop has some amazing flexibility built into it.
For example, if we want to, we can decrement i (i–) instead of incrementing it (i++).
We can also count by two’s, three’s, ten’s or what ever number we want. The code fragment below starts at 2 and counts by 11 as long as n is less than 124.
for (int n = 2; n < 124; n = n + 11)
Tired of numbers? Then count by characters:
for (char ch = 'a'; ch <= 'z'; ch++) printf("The ASCII value for %c is %d.\n", ch, ch);
This code fragment prints the ASCII value of each letter a though z. The code works because characters are stored as integers, so this loop is actually counting by integers.
You can leave one or more expressions within the for loop blank (don’t omit the semicolons). Just be sure to include within the loop itself some statement that eventually causes the loop to terminate.
And there is a myriad of other things one can do with a for loop.
C Programming: The while Loop
The while loop is another shiny diamond in the rough that you’ll often find yourself using.
It will loop continuously (and forever) until the expression inside the parenthesis becomes false. The syntax is shown here.
while(condition) { //do this stuff as long as condition is true… }
If condition is true (or nonzero, any nonzero value evaluates to true), the statement executes once and then the expression is tested again. This cycle of test and execution repeats until condition becomes false (or zero). Each cycle is an iteration of the loop.
Note that the condition is a Boolean expression and it either true or false. The condition can be many things like some sort of less than or equal comparison, the number 1 (which means true), or even a function.
This suggests an important point about while loops.
When you write a while loop, it must include something that changes the value of the test condition so that it eventually becomes false. Otherwise, the loop never terminates.
Consider the code snippet below.
while(1) { // This is an infinite loop! // 1 (or any other nonzero value -- even negative numbers) // is always considered true in the land of C. }
This snippet will loop forever. Believe it or not, there are times when this is appropriate.
A more practical example is shown below.
while( readADC() ) { //do stuff }
In this case, the loop will run as long as readADC() returns some sort of value that’s not 0.
Here’s another partial example demonstrating the while loop:
clock = 0; while(clock < 200) { // do something repetitive 200 times clock++; }
The ++ or incrementation operator has reared its head again and increments clock every time we go through the while loop to keep count.
A while Loop Gotcha
We touched on this last time, but it’s worth repeating because at some point I guarantee you will make a mistake like this. I know I did.
Remember from C Programming Tutorial 3 that the assignment operator (=) is not the same thing as the equal sign (==).
When doing a comparison with a while loop, you’ll likely be using == rather than the assignment operator.
Consider the code fragment below.
while (status = 1) { // Code goes here… }
The value of an assignment statement is the value of the left side, so status = 1 has the
same value as 1. So, this while loop is the same as using while (1). It never quits and loops infinitely.
Now consider the correct way.
while (status == 1) { // Code goes here… }
Try not to confuse = for ==. Some computer languages, like BASIC do use the same symbol for both the assignment operator and the equality operator, but the two operations are quite different.
The assignment operator assigns a value to the left variable. The equality operator simply checks to see if the left and right sides are already equal. It doesn’t change the value of the variable on the left.
Of course, the compiler may let you use the wrong form, bringing results that are odd and not what you expect.
C Program Control Final Points
At this point, you may be asking how do I know which loop or control structure to use and when?
A for loop is appropriate when the loop involves initializing and updating a variable. It’s a better choice for loops involving counting with an index, like the loop below.
for (count = 1; count <= 500; count++)
A while loop is better when the conditions are otherwise, like when we do not know what the initial value will be or how long it will be true. Consider the same code from earlier.
while (status == 1) { // Code goes here… }
We may not know how long status will be 1 (or true) so using an index wouldn’t make sense here. Situations like this is where the while loop really shines.
Of course, we can also use the while loop when we do know how many iterations we’ll have, like the code snippet below.
while (index < 5) printf("I love C!\n");
Before we wrap up, here are some key concepts to remember when using loops or any sort:
- Clearly define the condition that causes the loop to terminate (unless you want it to run forever)
- Be sure to initialize the values in the loop test before the first use
- Make sure the loop does something to update the test each iteration
Also, below is a handy chart that can help you decide which of the three control structures we discussed in this post to use. And yes, there are some control structures we didn’t discuss but we’ll pick those up next time.
Figure 1: C control structures from this post.
“C” you in the next tutorial!
Until then comment and tell us what you favorite C programming control structure or loop is. Why do you like it?
Become the Maker you were born to be. Try Arduino Academy for FREE!

Electronics Tips & Tutorials Sent Directly to Your Inbox

Submit your email & you'll get:
- Exclusive content that I don't put on the blog
- The checklist 10 mistakes all electronics enthusiasts make (& how to avoid them)
- And more!
I’ve always been a fan of the for loop. As you pointed out, it’s very flexible.