Loops – C

Loops are meant for executing statements multiple times. This improves code readability, increases development speed, reduces repetitive lines etc. in C there are three different loops – while, for, do while. Of which the first two are with pre-condition and last with post condition: do we ask first and then do?  Or do first and ask questions later

All of the loops have 2 special keywords which will change the program flow:

  • break – will exit the loop
    // outputs : 0 1 2 3
    for (int i = 0; i < 10; i++) {
        if (i == 4) {
            break;
        }
        printf("%d ", i);
    }
  • continue – will skip the execution of current iteration and jump back to the beginning of the next loop
    // outputs : 0 2 4 6 8
    for (int i = 0; i < 10; i++) {
        if (i % 2) {
            continue;
        }
        printf("%d ", i);
    }

 while

While loop executes code block as long as its condition is true. Since this loop has a pre condition the loop will not execute if the condition is evaluated as false.

Syntax:

while (expression) {
    /* Code block */
}

Representation in UML:

while loop

while loops:

  • are not guaranteed to run at least once
  • execute as long as the condition (expression) is true
  • should have something in the code block to change the state of expression
    • one might get an infinite loop if nothing changes in the loop, which should potentially end it
  • useful to use when it is unknown how many times loop should be executed
  • can be nested

do while

Do while has one key difference from while – it has a post condition. This means that the code block in the loop is executed at least once before the condition.

Syntax:

do {
    /* Code block */
} while (expression);

Representation in UML:

do while loop

do while loops:

  • guaranteed to be run at least once
  • post condition
  • should have something in the code block to change the state of expression
    • one might get an infinite loop if nothing changes in the loop, which should potentially end it
  • useful when asking for user input
    • ask until user stops giving invalid input
  • can be nested

for

For loop differs from the previous ones the most. It has 3 different sections in the parenthesis – initialization (giving initial value to variable / declare variable – C99 and C11), condition (expression) and post actions (statement which will be executed after each loop, usually incrementing variables value). All of the sections are separated by semicolons ‘;‘.

This loop is most commonly used and because of the three sections, it helps avoiding infinite loops.

Syntax:

for (initialization; condition; post_action) {
    /* Code block */
}

Representation in UML:

for loop

for loops:

  • are most commonly used loops
  • concise and easy to write / read
  • helps avoiding infinite loops
  • 3 sections are optional
    • if all sections are left blank, it is considered to be an infinite loop
  • can declare variable in first section since C99 standard
    • With older standards variable has to be declared before using it in a loop
  • can be nested

numbers as conditions

the condition “question” in a loop is, fundamentally, a number.  if that number is 0, then the condition is evaluated as “false”, if it’s anything else, the condition is evaluated as “true”.  this is an important distinction to make because sometimes the conditions of our program are more complex, or more abstract than simply comparing numbers, or counting to a number. for example:

  • go until we run out of data: while ( scanf() )
    •   the scanf function will return (be equal to) 0 if it fails to get any data, ending the loop
  • deliberate infinite loop:  while (1)
    • 1 will always be non-zero, and so this while loop will never end without a break

Example usage

Imagine having a program, which will measure room temperature and log it into a file. It will prompt the user to enter 1..10 measurements for averaging the temperature and this program should run infinitely (until stopped). This could be achieved simply by using all of the loops C language supports. Here is an example of how this program would look like:

#include <stdio.h>  // Standard Input / Output
#include "logger.h" // User defined library for logging
#include "temperature.h" // User defined library for measuring temperature
#include "delay.h"  // User defined library for delays

int main(void) {

    /* Initialization - set up program*/
    int measurement_points = 0;
    do {
        printf("Enter # of measurement points for averaging (1..10)\n");
        scanf("%d", &measurement_points);
    } while (measurement_points < 1 || measurement_points > 10);

    float measurements[measurement_points];
    float average_result = 0.0;

    /* Infinitely measure room temperature */
    while (1) { // Always evaluates to true
        // Reset result value
        average_result = 0.0;

        // Measure temperature
        for (int i = 0; i < measurement_points; i++) {
            measurements[i] = measure();
        }
        // Sum measurements
        for (int i = 0; i < measurement_points; i++) {
            average_result += measurements[i];
        }
        // Calculate average
        average_result /= (float)measurement_points;
        // Log results
        log(average_result);

        // wait for 10 minutes
        delay_s(60*10);
    }    
    
    return 0;
}

 

NB! The included user libraries do not exist!

Common mistakes

  • No post loop action
  • Condition is infinitely true
  • Condition is never true
  • Adding semicolon after the braces

Resources

  1. C Loops [ Link ]

One thought on “Loops – C

Comments are closed.