www.easyCPlusPlus.com

Easy C++

www.easyCPlusPlus.com

C Tutorial - Lesson 7: Looping

Do, While and For Constructs

by John Kopp

Support this site at no cost to you

Welcome to easyCPlusPlus.com's C tutorial. This lesson covers three constructs that are used to create loops in C programs. Loops can be created to execute a block of code for a fixed number of times. Alternatively, loops can be created to repetitively execute a block of code until a boolean condition changes state. For instance, the loop may continue until a condition changes from false to true, or from true to false. In this case, the block of code being executed must update the condition being tested in order for the loop to terminate at some point. If the test condition is not modified somehow within the loop, the loop will never terminate. This creates a programming bug known as an infinite loop.

While
The while loop is used to execute a block of code as long as some condition is true. If the condition is false from the start the block of code is not executed at all. Its syntax is as follows.

while (tested condition is satisfied) {
    block of code
}

Here is a simple example of the use of while. This program counts from 1 to 100.

#include <stdio.h>

int main()
{
    int count = 1;

    while (count <= 100)
    {
        printf("%d\n",count);
        count += 1; /* Shorthand for count = count + 1 */
    }

    return 0;
}

Here is a more realistic use of while. This program determines the minimum number of bits needed to store a positive integer. The largest unsigned number that can be stored in N bits is (2N - 1).

#include <stdio.h>

int main()
{
    int bitsRequired = 1; //the power of 2
    int largest = 1; //largest number that can be stored
    int powerOf2 = 2;
    int number;

    printf("Enter a positive integer: ");
    scanf("%d",&number);

    while (number > largest)
    {
        bitsRequired += 1; //Shorthand for bitsRequired = bitsRequired + 1
        powerOf2 = powerOf2 * 2;
        largest = powerOf2 - 1;
    }

    printf("To store %d requires %d bits",number,bitsRequired);

    return 0;
}

Previous Page       Next Page