Yes, You Can Nest while Loops

Somewhere in my vast array of teaching material, I claimed that only for loops can be nested. That’s poppycock.

You can nest any type of loop in the C language, or in any programming language. A while loop nests just as snugly as a for loop. In fact, you can convert any for loop into a while loop, no problem. Some programmers find while loops more readable, which is a sentiment I share.

In the following code, nested while loops generate a grid of numbers and letters:

#include <stdio.h>

int main()
{
    short a;
    char b;

    a = 1;
    while(a <= 5)
    {
        b = 'A';
        while(b <= 'E')
        {
            printf("%d%c\t",a,b);
            b++;
        }
        putchar('\n');
        a++;
    }

    return(0);
}

The while loop at Line 9 spins 5 times. The while loop at Line 12 also spins 5 times, but uses char variable b and characters 'A' through 'F' instead of values. (Well, internally these characters are values.)

Here’s the output:

1A	1B	1C	1D	1E	
2A	2B	2C	2D	2E	
3A	3B	3C	3D	3E	
4A	4B	4C	4D	4E	
5A	5B	5C	5D	5E

A for loop can accomplish the same thing, but in fewer lines. That’s because the various pieces of the loop are contained in a single statement as opposed to separate lines in the code.

For example, a for loop for variable a would combine Lines 8, 9, and 18 into a single statement:

for(a=1; a<=5; a++)

Ditto for variable b:

for(b='A'; b<='E'; b++)

Here is the for version of the same code:

#include <stdio.h>

int main()
{
    short a;
    char b;

    for(a=1; a<=5; a++)
    {
        for(b='A'; b<='E'; b++)
            printf("%d%c\t",a,b);
        putchar('\n');
    }

    return(0);
}

And the output is the same, though the code is 6 lines shorter.

Which is best? Neither, though again I believe that the while loop example is more readable. Still, my point is that you can nest both for and while loops. You can even mix them. If I wrote or said that you can’t nest a while loop I was just being silly.

Leave a Reply