Implementing while Loops in C

Repetitive Programming Using the While Keyword in C/C++

© Guy Lecky-Thompson

How to construct an outer while loop which tests to see whether a program should exit based on user input.

Often, a programmer will want to construct a program which performs some processing, and then asks the user if they want to run the program again.

Since there is no way of knowing, in advance, how many runs of the software should be performed, the only loop that can be used is a while loop. Depending on what the exit condition should be, this must be combined with some processing from stdio.h and string.h, to:

Before moving on to some concrete examples, there are a few things that the programmer needs to know about while loops.

The while Loop

There are two forms of while loop in C programming. The first performs the evaluation of the value to be tested at the start of the while loop:

while ( <condition> ) {
  // processing here
}

Since the condition is evaluated at the start of the loop, this is clearly no use if the software has to perform some processing before making that evaluation. In this case, where the user is being invited to make another run of the program, another form of the while loop is needed:

do {
  // processing here
} while ( <condition>);

In this form, the do keyword marks the start of the loop, which will execute as long as the condition evaluates to 'true'. As soon as the condition is 'false', the loop will end. In this solution, everything that makes up the program needs to go between the do { and } while (); statements. Everything, that is, except any initialization of variables needed in the program.

Testing the User Input

If it is assumed that the user will be invited to enter 'Yes' or 'No' in order to end (or not) the program, then the stdio.h library will be needed to read in the value to be tested. In the following code, the variable szChoice has to be defined somewhere sensible in the program.

printf("Another run (Yes/No)?");
scanf("%s", szChoice);

At this point, it is necessary to test the szChoice variable against either 'Yes' or 'No'. Bearing in mind that the loop will execute until the condition returns false, the test should be for inequality against 'Yes', or equality against 'No'. The strcmp function will return a non-zero result if the two strings are equal.

So, the following code will do what is needed:

while ( strcmp( szChoice, "Yes" ) );

The above works by comparing szChoice with 'Yes'. This means that the user has to explicitly type in 'Yes' (without the quotes) to run the program again. To make it case insensitive (i.e. YES, yes, YeS and yES are equivalent), then the stricmp function can be used.

The Esoteric Solution

There is another solution, which is a little esoteric. This involves the use of the break keyword to prematurely end the loop.

do {
  // Some processing
  printf("Another run (Yes/No)?");
  scanf("%s", &szChoice);
  if ( stricmp ( szChoice, "No" ) ) break;
} while ( 1 ); // Always 'true'

The above illustrates the use of an if clause and an infinite while loop, that will never exit unless the break keyword is called. The reader should also notice that the example has to test against the exit clause 'No', as it tests for 'true' and not 'false'.

Should the stricmp function not be available in the string.h library (it is not part of the C99 standard), then changing the string to uppercase (or lowercase) can be done using functions from the stdlib.h library, or by explicitly manipulating the ASCII code. Of course, in the interest of portability, it is better to use the library functions as they do not depend on knowledge of the underlying character encoding mechanism.


The copyright of the article Implementing while Loops in C in C Programming is owned by Guy Lecky-Thompson. Permission to republish Implementing while Loops in C must be granted by the author in writing.



Comments
May 7, 2008 12:12 PM
Dario Borghino :
Hi!
Good article, but I found a couple errors in the code.

1. szChoice is a string, you shouldn't reference it with '&' when scanf()ing.
2. you can avoid buffer overflow attacks by using strncmp() instead of strcmp(). A simple scanf() is also not recommendable for the same reason -- use fgets() instead.
3. stricmp() is not part of the C99 standard library.
4. in production code, 'while(1)' is much more common than 'while(1 == 1)'.

Hope this is useful!
Page:
1 Comment:

Post this Article to facebook Add this Article to del.icio.us! Digg this Article furl this Article Add this Article to Reddit Add this Article to Technorati Add this Article to Newsvine Add this Article to Windows Live Add this Article to Yahoo Add this Article to StumbleUpon Add this Article to BlinkLists Add this Article to Spurl Add this Article to Google Add this Article to Ask Add this Article to Squidoo