Program Looping in C: The while Statement

The while statement further extends the C language’s repertoire of looping capabilities. The syntax of this frequently used construct is as follows:

while ( expression )

program statement

The expression specified inside the parentheses is evaluated. If the result of the expression evaluation is TRUE, the program statement that immediately follows is executed. After execution of this statement (or statements if enclosed in braces), the expression is once again evaluated. If the result of the evaluation is TRUE, the program statement is once again executed. This process continues until the expression finally evaluates  as FALSE, at which point the loop is terminated. Execution of the program then continues with the statement that follows the program statement.

As an example of its use, Program 5.6 sets up a while loop, which merely counts from 1 to 5.

 

Program 5.6   Introducing  the while Statement

// Program to introduce the while statement

#include <stdio.h>

int main (void)

{

int count = 1;

while ( count <= 5 ) {

printf (“%i\n”, count);

++count;

}

return 0;

}

Program 5.6 Output

1

2

3

4

5

The program initially sets the value of count to 1. Execution of the while loop then begins. Because the value of count is less than or equal to 5, the statement that immedi- ately follows is executed. The braces serve to define both the printf statement and the statement that increments count as the body of the while loop. From the output of the program, you can readily observe that this loop is executed precisely 5 times, or until the value of count reaches 6.

You might have realized from this program that you could have readily accomplished the same task by using a for statement. In fact, a for statement can always be translated into an equivalent while statement, and vice versa. For example, the general for statement

for ( init_expressionloop_conditionloop_expression )

program statement

can be equivalently expressed in the form of a while statement as

init_expression;

while ( loop_condition ) {

program statement

loop_expression;

}

After you become familiar with the use of the while statement, you will gain a better feel as to when it seems more logical to use a while statement and when to use a for statement.

In general, a loop executed a predetermined number of times is a prime candidate for implementation as a for statement. Also, if the initial expression, looping expression, and looping condition all involve the same variable, the for statement is probably the right choice.

The next program provides another example of the use of the while statement. The program computes the greatest common divisor of two integer values. The greatest common divisor (gcd) of two integers is the largest integer value that evenly divides the two inte- gers. For example, the gcd of 10 and 15 is 5 because 5 is the largest integer that evenly divides both 10 and 15.

There is a procedure or algorithm that can be followed to arrive at the gcd of two arbi- trary integers. This algorithm is based on a procedure originally developed by Euclid around 300 B.C., and can be stated as follows:

Problem:               Find the greatest common divisor of two nonnegative integers u and v.

Step 1:                  If v equals 0, then you are done and the gcd is equal to u.

Step 2:                  Calculate temp = u % v, u = v, v = temp, and go back to step 1.

Don’t concern yourself with the details of how the preceding algorithm works—simply take it on faith. Focus more here on developing the program to find the greatest com- mon divisor than on performing an analysis of how the algorithm works.

After the solution to the problem of finding the greatest common divisor has been expressed in terms of an algorithm, it becomes a much simpler task to develop the com- puter program. An analysis of the steps of the algorithm reveals that step 2 is repetitively executed as long as the value of v is not equal to 0. This realization leads to the natural implementation of this algorithm in C with the use of a while statement.

Program 5.7 finds the gcd of two nonnegative integer values typed in by the user.

 

Program 5.7   Finding the Greatest Common Divisor

/* Program to find the greatest common divisor

of two nonnegative integer values        */

#include <stdio.h>

int main (void)

{

int u, v, temp;

printf (“Please type in two nonnegative integers.\n”);

scanf (“%i%i”, &u, &v);

while ( v != 0 ) {

temp = u % v;

u = v;

v = temp;

}

printf (“Their greatest common divisor is %i\n”, u);

return 0;

}

Please type in two nonnegative integers.

150 35

Their greatest common divisor is 5

Program 5.7   Output (Rerun)

Please type in two nonnegative integers.

1026 405

Their greatest common divisor is 27

The double %i characters in the scanf call indicate that two integer values are to be entered from the keyboard. The first value that is entered is stored in the integer variable u, whereas the second value is stored in the variable v. When the values are actually entered from the terminal, they can be separated from each other by one or more blank spaces or by a carriage return.

After the values have been entered from the keyboard and stored in the variables u and v, the program enters a while loop to calculate their greatest common divisor. After the while loop is exited, the value of u, which represents the gcd of v and the original value of u, is displayed at the terminal, together with an appropriate message.

Program 5.8 illustrates another use of the while statement, the task of reversing the digits of an integer that is entered from the terminal. For example, if the user types in the number 1234, you want the program to reverse the digits of this number and display the result of 4321.

To write such a program, you first must come up with an algorithm that accomplish- es the stated task. Frequently, an analysis of your own method for solving the problem leads to the development of an algorithm. To reverse the digits of a number, the method of solution can be simply stated as “successively  read the digits of the number from right to left.”You can have a computer program “successively read” the digits of the number by developing a procedure to successively isolate or “extract” each digit of the number, beginning with the rightmost digit. The extracted digit can be subsequently displayed at the terminal as the next digit of the reversed number.

You can extract the rightmost digit from an integer number by taking the remainder of the integer after it is divided by 10. For example, 1234 % 10 gives the value 4, which is the rightmost digit of 1234, and is also the first digit of the reversed number. (Remember the modulus operator, which gives the remainder of one integer divided by another.) You can get the next digit of the number by using the same process if you first divide the number by 10, bearing in mind the way integer division works. Thus, 1234 /10 gives a result of 123, and 123 % 10 gives us 3, which is the next digit of your reversed number.

This procedure can be continued until the last digit has been extracted. In the general case, you know that the last digit of the number has been extracted when the result of the last integer division by 10 is 0.

Program 5.8   Reversing  the Digits  of a Number

// Program to reverse the digits of a number

#include <stdio.h>

int main (void)

{

int number, right_digit;

printf (“Enter your number.\n”);

scanf (“%i”, &number);

while ( number != 0 ) {

right_digit = number % 10;

printf (“%i”, right_digit);

number = number / 10;

}

printf (“\n”);

return 0;

}

Program 5.8   Output

Enter your number.

13579

97531

Each digit is displayed  as it is extracted by the program. Notice that you did not include a newline character inside the printf statement contained in the while loop. This forces each successive digit to be displayed on the same line. The final printf call at the end of the program contains just a newline character, which causes the cursor to advance to the start of the next line.

Source: Kochan Stephen G. (2004), Programming in C: A Complete Introduction to the C Programming Language, Sams; Subsequent edition.

Leave a Reply

Your email address will not be published. Required fields are marked *