Absurd: An Introduction to C

Part III, 20120626

So, in this installment, let's talk about loops. So far, all you have had is sequences. Programs only consist of sequence, loop, selection, and data. Looking at it this way, you're nearly ready to call yourself a programmer. So, don't get discouraged.

A loop does something while a certain condition is met or not met. The most straight forward type of loop is therefore the while loop

#include <stdio.h>
int main( void ) {
  int count = 0;
  while (count < 11) {
    printf("\nThe value of count is currently %d\n", count);
    count++;
  }
  return 0;
}

So, we include the usual stdio.h (despite the fact that this example, like the others, really doesn't need it; the compiler will spit warnings at you if you don't include it). Next we declare out function main. We then declare and initialize an integer variable named count. The interesting part is our loop.

All while loops will start with "while ( condition )" and in our case "while (count < 11)" is: while the integer variable count is less than 11. The contents of the while loop are contained within the braces just like the contents of the function main. The only other thing to note is that we are using the increment operator "++" on count. If you remember this is equivalent to "count = count + 1".

The next type of loop to look at is the do-while. This isn't much different.

#include <stdio.h> 
int main( void ) {
  int i = 0;
  do {
    printf("The value of i is currently %d\n", i);
    i++;
  } while (i < 10);
  return 0;
}

Like I said, not much different. The key difference is that the test is done after each iteration of the loop. This means that the logic contained within the braces will always be executed at least once. In both forms of the while loop, if you do not change your test variable the loop will never exit (terminate).

#include <stdio.h>
int main( void ) {
  int i;
  for (i = 0; i <= 10; i++) {
    printf("The value of i is currently %d\n" i);
  }
  return 0;
}

This one actually is a little different from the other two. In this one, following the "for" (all of these types of words all called "reserved words" because they are "reserved" for the language and compiler as commands) there are three fields which make up your test for the loop. The first one initializes the variable i. The second says that we will run this loop so long as i is less than or equal to (yup just tossed something new in there) 10, and the third increments the variable i by one for each pass through the loop. Otherwise, this application is essentially the same as those preceding it.

If you want to get some experience with these different loops, go ahead and play with all three types. Try changing up the tests and using different arithmetic to change the variable. There are "<=" (less than or equal to), ">=" (greater than or equal to), "<" (less than), ">" (greater than), and "==" (equal to) for tests.

⇠ back

© MMIX - MMXX, absurd.wtf
Licentiam Absurdum