Programming C While Loops on The Raspberry Pi

Download PDF

Writing C While Loops

c while loopsIn the last blog we did use a C while loop to help us iterate though the supplied arguments, as a result we can then check what code we need to run. Using a simpler loop we can see more detail on how they work and where we can use these tools. Using a C while loop we will count down from 10 to 0 and finally print finished to the screen.

Very Simple Code

If we just want to see a while loop up and running then our code can be very quick and we can have the program up and running in little time.

#include <stdio.h>

int main () {

  int c = 10;
  while ( c > -1 ) {
    printf("%d ", c);
    c--;
  }
  printf("\nFinished\n");
  return 0;
}

Looking at the code it is good an does do what we want but the count down is too quick. We test for the counter variable c being greater than -1. Starting at 10 this means that we count from 10 until 0. Using printf we can print the variable and then we decrease the value of the counter c by 1. This is with the line c–;. If we need to count up rather than down we would increment with c++;. Running the code though we do see the numbers appear at the same time.

Slowing Down the Loop

The C while loop that we use happens just a little to frantically for us and we need to allow it to chill a little. The sleep function can help with this and we will find it in the unistd.h. The function sleep(1) will pause for 1 second.

#include <stdio.h>
#include <unistd.h>

int main () {

  int c = 10;
  while ( c > -1 ) {
    printf("%d ", c);
    sleep(1);
    c--;
  }
  printf("\nFinished\n");
  return 0;
}

This now need to be compiled and executed again. We should see the program now waits 10 seconds before displaying anything but still prints all at once. This is because printf will buffer when printing to a console. We need to flush the buffers each time with fflush.

The Working Example

#include <stdio.h>
#include <unistd.h>

int main () {

  int c = 10;
  while ( c > -1 ) {
    printf("%d ", c);
    fflush(stdout);
    sleep(1);
    c--;
  }
  printf("\nFinished\n");
  return 0;
}

Using fflush from the stdio.h we are able to flush the named stream, stdout in this case. Now we print each time and cont down from 10 to 0 more slowly. We now have now seen how to create working C While loops.