Program Looping - Programming in C (Fourth Edition) (2015)

Programming in C (Fourth Edition) (2015)

4. Program Looping

One of the great powers of computers is their ability to perform repeated calculations. The C program has a few constructs specifically designed to handle these situations when you need to use the same code repeatedly. This chapter will help you understand these tools, including

Image The for statement

Image The while statement

Image The do statement

Image The break statement

Image The continue statement

Triangular Numbers

If you arrange 15 dots in the shape of a triangle, you end up with an arrangement that might look something like this:


• •
• • •
• • • •
• • • • •

The first row of the triangle contains one dot, the second row contains two dots, and so on. In general, the number of dots it takes to form a triangle containing n rows is the sum of the integers from 1 through n. This sum is known as a triangular number. If you start at 1, the fourth triangular number is the sum of the consecutive integers 1 through 4 (1 + 2 + 3 + 4), or 10.

Suppose you want to write a program that calculates and displays the value of the eighth triangular number at the terminal. Obviously, you could easily calculate this number in your head, but for the sake of argument, assume that you want to write a program in C to perform this task. Such a program is shown in Program 4.1.

The technique of Program 4.1 works fine for calculating relatively small, triangular numbers. But what happens if you need to find the value of the 200th triangular number, for example? It certainly would be tedious to modify Program 4.1 to explicitly add up all of the integers from 1 to 200. Luckily, there is an easier way.

Program 4.1 Calculating the Eighth Triangular Number


// Program to calculate the eighth triangular number

#include <stdio.h>

int main ()
{
int triangularNumber;

triangularNumber = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8;

printf ("The eighth triangular number is %i\n", triangularNumber);

return 0;
}


Program 4.1 Output


The eighth triangular number is 36


One of the fundamental properties of a computer is its ability to repetitively execute a set of statements. These looping capabilities enable you to develop concise programs containing repetitive processes that could otherwise require thousands or even millions of program statements to perform. The C programming language contains three different program statements for program looping. They are known as the for statement, the while statement, and the do statement. Each of these statements is described in detail in this chapter.

The for Statement

Let’s dive right in and take a look at a program that uses the for statement. The purpose of Program 4.2 is to calculate the 200th triangular number. See if you can determine how the for statement works.

Program 4.2 Calculating the 200th Triangular Number


/* Program to calculate the 200th triangular number
Introduction of the for statement */

#include <stdio.h>

int main (void)
{
int n, triangularNumber;

triangularNumber = 0;

for ( n = 1; n <= 200; n = n + 1 )
triangularNumber = triangularNumber + n;

printf ("The 200th triangular number is %i\n", triangularNumber);

return 0;
}


Program 4.2 Output


The 200th triangular number is 20100


Some explanation is needed for Program 4.2. The method employed to calculate the 200th triangular number is really the same as that used to calculate the 8th triangular number in Program 4.1—the integers from 1 to 200 are summed. The for statement provides the mechanism that enables you to avoid having to explicitly write out each integer from 1 to 200. In a sense, this statement is used to “generate” these numbers for you.

The general format of the for statement is as follows:

for ( init_expression; loop_condition; loop_expression )
program statement (or statements)

The three expressions that are enclosed within the parentheses—init_expression, loop_condition, and loop_expression—set up the environment for the program loop. The program statement that immediately follows (which is, of course, terminated by a semicolon) can be any valid C program statement and constitutes the body of the loop. This statement is executed as many times as specified by the parameters set up in the for statement.

The first component of the for statement, labeled init_expression, is used to set the initial values before the loop begins. In Program 4.2, this portion of the for statement is used to set the initial value of n to 1. As you can see, an assignment is a valid form of an expression.

The second component of the for statement are the condition or conditions that are necessary for the loop to continue. In other words, looping continues as long as this condition is satisfied. Once again referring to Program 4.2, note that the loop_condition of the for statement is specified by the following relational expression:

n <= 200

This expression can be read as “n less than or equal to 200.” The “less than or equal to” operator (which is the less than character < followed immediately by the equal sign =) is only one of several relational operators provided in the C programming language. These operators are used to test specific conditions. The answer to the test is “yes” or, more commonly, TRUE if the condition is satisfied and “no” or FALSE if the condition is not satisfied.

Relational Operators

Table 4.1 lists all the relational operators that are available in C.

Image

Table 4.1 Relational Operators

The relational operators have lower precedence than all arithmetic operators. This means, for example, that the following expression

a < b + c

is evaluated as

a < (b + c)

as you would expect. It would be TRUE if the value of a were less than the value of b + c and FALSE otherwise.

Pay particular attention to the “is equal to” operator == and do not confuse its use with the assignment operator =. The expression

a == 2

tests if the value of a is equal to 2, whereas the expression

a = 2

assigns the value 2 to the variable a.

The choice of which relational operator to use obviously depends on the particular test being made and in some instances on your particular preferences. For example in Program 4.2, the relational expression

n <= 200

can be equivalently expressed as

n < 201

The program statement that forms the body of the for loop

triangularNumber = triangularNumber + n;

is repetitively executed as long as the result of the relational test is TRUE, or in this case, as long as the value of n is less than or equal to 200. This program statement has the effect of adding the value of triangularNumber to the value of n and storing the result back in the value oftriangularNumber.

When the loop_condition is no longer satisfied, execution of the program continues with the program statement immediately following the for loop. In your program, execution continues with the printf statement after the loop has terminated.

The final component of the for statement contains an expression that is evaluated each time after the body of the loop is executed. In Program 4.2, this loop_expression adds 1 to the value of n. Therefore, the value of n is incremented by 1 each time after its value has been added into the value of triangularNumber and ranges in value from 1 to 201.

It is worth noting that the last value that n attains, namely 201, is not added into the value of triangularNumber because the loop is terminated as soon as the looping condition is no longer satisfied, or as soon as n equals 201.

In summary, execution of the for statement proceeds as follows:

1. The initial expression is evaluated first. This expression usually sets a variable that will be used inside the loop, generally referred to as an index variable, to some initial value such as 0 or 1.

2. The looping condition is evaluated. If the condition is not satisfied (the expression is FALSE), the loop is immediately terminated. Otherwise, execution continues with the program statement that immediately follows the loop.

3. The program statement that constitutes the body of the loop is executed.

4. The looping expression is evaluated. This expression is generally used to change the value of the index variable, frequently by adding an incremental variable to it or subtracting an decremental variable from it.

5. Return to step 2.

Remember that the looping condition is evaluated immediately on entry into the loop, before the body of the loop has even executed one time. Also, remember not to put a semicolon after the close parenthesis at the end of the loop (this immediately ends the loop).

Because Program 4.2 actually generates all of the first 200 triangular numbers on its way to its final goal, it might be nice to generate a table of these numbers. To save space, however, let’s assume that you just want to print a table of the first 10 triangular numbers. Program 4.3 performs precisely this task!

Program 4.3 Generating a Table of Triangular Numbers


// Program to generate a table of triangular numbers

#include <stdio.h>

int main (void)
{
int n, triangularNumber;

printf ("TABLE OF TRIANGULAR NUMBERS\n\n");
printf (" n Sum from 1 to n\n");
printf ("--- ---------------\n");

triangularNumber = 0;

for ( n = 1; n <= 10; ++n ) {
triangularNumber += n;
printf (" %i %i\n", n, triangularNumber);
}

return 0;
}


Program 4.3 Output


TABLE OF TRIANGULAR NUMBERS

n Sum from 1 to n
--- ---------------
1 1
2 3
3 6
4 10
5 15
6 21
7 28
8 36
9 45
10 55


It is always a good idea to add some extra printf() statements to a program to provide more meaning to the output. In Program 4.3, the purpose of the first three printf() statements is simply to provide a general heading and to label the columns of the output. Notice that the firstprintf() statement contains two newline characters. As you would expect, this has the effect of not only advancing to the next line, but also inserting an extra blank line into the display.

After the appropriate headings have been displayed, the program proceeds to calculate the first 10 triangular numbers. The variable n is used to count the current number whose “sum from 1 to n" you are computing, whereas the variable triangularNumber is used to store the value of triangular number n.

Execution of the for statement commences by setting the value of the variable n to 1. Remember that the program statement immediately following the for statement constitutes the body of the program loop. But what happens if you want to repetitively execute not just a single program statement, but a group of program statements? This can be accomplished by enclosing all such program statements within a pair of braces. The system then treats this group or block of statements as a single entity. In general, any place in a C program that a single statement is permitted, a block of statements can be used, provided that you remember to enclose the block within a pair of braces.

Therefore, in Program 4.3, both the expression that adds n into the value of triangularNumber and the printf() statement that immediately follows constitute the body of the program loop. Pay particular attention to the way the program statements are indented. It is easy to determine which statements form part of the for loop. You should also note that programmers use different coding styles. Some prefer to type the loop this way:

for ( n = 1; n <= 10; ++n )
{
triangularNumber += n;
printf (" %i %i\n", n, triangularNumber);
}

Here, the opening brace is placed on the next line after the for. This is strictly a matter of taste and has no effect on the program.

The next triangular number is calculated by simply adding the value of n to the previous triangular number. This time, the “plus equals” operator is used, which was introduced in Chapter 3, “Variables, Data Types, and Arithmetic Expressions.” Recall that the expression

triangularNumber += n;

is equivalent to the expression

triangularNumber = triangularNumber + n;

The first time through the for loop, the “previous” triangular number is 0, so the new value of triangularNumber when n is equal to 1 is simply the value of n, or 1. The values of n and triangularNumber are then displayed, with an appropriate number of blank spaces inserted in the format string to ensure that the values of the two variables line up under the appropriate column headings.

Because the body of the loop has now been executed, the looping expression is evaluated next. The expression in this for statement appears a bit strange, however. It seems like you made a typographical mistake and meant to insert the expression

n = n + 1

instead of the funny-looking expression

++n

The expression ++n is actually a perfectly valid C expression. It introduces you to a new (and rather unique) operator in the C programming language—the increment operator. The function of the double plus sign—or the increment operator—is to add 1 to its operand. Because addition by 1 is such a common operation in programs, a special operator was created solely for this purpose. Therefore, the expression ++n is equivalent to the expression n = n + 1. Although it might appear that n = n + 1 is more readable, you will soon become familiar with the function of this operator and will even learn to appreciate its succinctness.

Of course, no programming language that offered an increment operator to add 1 would be complete without a corresponding operator to subtract 1. The name of this operator is the decrement operator and is symbolized by the double minus sign. So, an expression in C that reads

bean_counter = bean_counter - 1

can be equivalently expressed using the decrement operator as

--bean_counter

Some programmers prefer to put the ++ or -- after the variable name, as in n++ or bean_counter--. This is a matter of personal preference for the example shown in the for statement. However, as you’ll learn in Chapter 10, “Pointers,” the pre- or post-nature of the operator does come into play when used in more complex expressions.

Aligning Output

One slightly disturbing thing that you might have noticed in Program 4.3’s output is the fact that the 10th triangular number does not quite line up under the previous triangular numbers. This is because the number 10 takes up two print positions, whereas the previous values of n, 1 through 9, took up only one print position. Therefore, the value 55 is effectively “pushed over” one extra position in the display. This minor annoyance can be corrected if you substitute the following printf() statement in place of the corresponding statement from Program 4.3.

printf ("%2i %i\n", n, triangularNumber);

To verify that this change does the trick, here is the output from the modified program (we’ll call it Program 4.3A).

Program 4.3A Output


TABLE OF TRIANGULAR NUMBERS

n Sum from 1 to n
--- ---------------
1 1
2 3
3 6
4 10
5 15
6 21
7 28
8 36
9 45
10 55


The primary change made to the printf() statement was the inclusion of a field width specification. The characters %2i tell the printf() routine that not only do you want to display the value of an integer at that particular point, but you also want the size of the integer to be displayed to take up two columns in the display. Any integer that would normally take up less than two columns (that is, the integers 0 through 9) are displayed with a leading space. This is known as right justification.

Thus, by using a field width specification of %2i, you guarantee that at least two columns are used for displaying the value of n and, therefore, you ensure that the values of triangularNumber are lined up.

If the value that is to be displayed requires more columns than are specified by the field width, printf() simply ignores the field width specification and uses as many columns as are necessary to display the value.

Field width specifications can also be used for displaying values other than integers. You will see some examples of this in programs that are coming up shortly.

Program Input

Program 4.2 calculates the 200th triangular number—and nothing more. If you want to calculate the 50th or the 100th triangular number instead, you have to go back and change the program so that the for loop is executed the correct number of times. You also have to change theprintf() statement to display the correct message.

An easier solution might be if you could somehow have the program ask which triangular number you want to calculate. Then, after you provide your answer, the program could calculate the desired triangular number for you. Such a solution can be effected in C by using a routine calledscanf(). The scanf() routine is very similar in concept to the printf routine. Whereas the printf() routine is used to display values at the terminal, the scanf() routine enables you to type values into the program. Program 4.4 asks the user which triangular number should be calculated, proceeds to calculate that number, and then displays the results.

Program 4.4 Asking the User for Input


#include <stdio.h>

int main (void)
{
int n, number, triangularNumber;

printf ("What triangular number do you want? ");
scanf ("%i", &number);

triangularNumber = 0;

for ( n = 1; n <= number; ++n )
triangularNumber += n;

printf ("Triangular number %i is %i\n", number, triangularNumber);

return 0;
}


In Program 4.4 output, the number typed in by the user (100) is set in bold type to distinguish it from the output displayed by the program.

Program 4.4 Output


What triangular number do you want? 100
Triangular number 100 is 5050


According to the output, the number 100 was typed in by the user. The program then proceeded to calculate the 100th triangular number and displayed the result of 5050 at the terminal. The user could have instead typed in the number 10, or 30, if he desired to calculate those particular triangular numbers.

The first printf() statement in Program 4.4 is used to prompt the user to type in a number. Of course, it is always nice to remind the user what it is you want entered. After the message is printed, the scanf() routine is called. The first argument to scanf() is the format string and is very similar to the format string used by printf(). In this case, the format string doesn’t tell the system what types of values are to be displayed but rather what types of values are to be read in from the terminal. Like printf(), the %i characters are used to specify an integer value.

The second argument to the scanf() routine specifies where the value that is typed in by the user is to be stored. The & character before the variable number is necessary in this case. Don’t worry about its function here, though. Chapter 10 discusses this character, which is actually an operator, in great detail. Always remember to put the leading & in front of the variable name in the scanf() function call. If you forget, it causes unpredictable results and might cause your program to terminate abnormally.

Given the preceding discussion, you can now see that the scanf() call from Program 4.4 specifies that an integer value is to be read from the terminal and stored in the variable number. This value represents the particular triangular number that the user wants to calculate.

After this number has been typed in (and the “Return” or “Enter” key on the keyboard pressed to signal that typing of the number is completed), the program then proceeds to calculate the requested triangular number. This is done in the same way as in Program 4.2—the only difference being that instead of using 200 as the limit, number is used.


Note

Pressing the Enter key on a keyboard with a numeric keypad may not cause the number you enter to be sent to the program. Use the Return key on your keyboard instead.


After the desired triangular number has been calculated, the results are displayed, and execution of the program is then complete.

Nested for Loops

Program 4.4 gives the user the flexibility to have the program calculate any triangular number that is desired. However, if the user has a list of five triangular numbers to be calculated, she can simply execute the program five times, each time typing in the next triangular number from the list to be calculated.

Another way to accomplish this same goal, and a far more interesting method as far as learning about C is concerned, is to have the program handle the situation. This can best be accomplished by inserting a loop in the program to simply repeat the entire series of calculations five times. You know by now that the for statement can be used to set up such a loop. Program 4.5 and its associated output illustrate this technique.

Program 4.5 Using Nested for Loops


#include <stdio.h>

int main (void)
{
int n, number, triangularNumber, counter;

for ( counter = 1; counter <= 5; ++counter ) {
printf ("What triangular number do you want? ");
scanf ("%i", &number);

triangularNumber = 0;

for ( n = 1; n <= number; ++n )
triangularNumber += n;

printf ("Triangular number %i is %i\n\n", number, triangularNumber);
}

return 0;
}


Program 4.5 Output


What triangular number do you want? 12
Triangular number 12 is 78

What triangular number do you want? 25
Triangular number 25 is 325

What triangular number do you want? 50
Triangular number 50 is 1275

What triangular number do you want? 75
Triangular number 75 is 2850

What triangular number do you want? 83
Triangular number 83 is 3486


The program consists of two levels of for statements. The outermost for statement

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

specifies that the program loop is to be executed precisely five times. This can be seen because the value of counter is initially set to 1 and is incremented by 1 until it is no longer less than or equal to 5 (in other words, until it reaches 6).

Unlike the previous program examples, the variable counter is not used anywhere else within the program. Its function is solely as a loop counter in the for statement. Nevertheless, because it is a variable, it must be declared in the program.

The program loop actually consists of all the remaining program statements, as indicated by the braces. It might be easier for you to comprehend the way this program operates if you conceptualize it as follows:

For 5 times
{
Get the number from the user.

Calculate the requested triangular number.

Display the result.
}

The portion of the loop referred to in the preceding as Calculate the requested triangular number actually consists of setting the value of the variable triangularNumber to 0 plus the for loop that calculates the triangular number. Thus, you see that you have a for statement that is actually contained within another for statement. This is perfectly valid in C, and nesting can continue even further to any desired level.

The proper use of indentation becomes even more critical when dealing with more sophisticated program constructs, such as nested for statements. You can easily determine which statements are contained within each for statement. (To see how unreadable a program can be if correct attention isn’t paid to formatting, see exercise 5 at the end of this chapter.)

for Loop Variants

Some syntactic variations are permitted in forming the for loop. When writing a for loop, you might discover that you have more than one variable that you want to initialize before the loop begins or more than one expression that you want to evaluate each time through the loop.

Multiple Expressions

You can include multiple expressions in any of the fields of the for loop, provided that you separate such expressions by commas. For example, in the for statement that begins

for ( i = 0, j = 0; i < 10; ++i )
...

the value of i is set to 0 and the value of j is set to 0 before the loop begins. The two expressions i = 0 and j = 0 are separated from each other by a comma, and both expressions are considered part of the init_expression field of the loop. As another example, the for loop that starts

for ( i = 0, j = 100; i < 10; ++i, j = j - 10 )
...

sets up two index variables, i and j; the former initialized to 0 and the latter to 100 before the loop begins. Each time after the body of the loop is executed, the value of i is incremented by 1, whereas the value of j is decremented by 10.

Omitting Fields

Just as the need might arise to include more than one expression in a particular field of the for statement, the need might arise to omit one or more fields from the statement. This can be done simply by omitting the desired field and marking its place with a semicolon. The most common application for the omission of a field in the for statement occurs when there is no initial expression that needs to be evaluated. The init_expression field can simply be “left blank” in such a case, as long as the semicolon is still included:

for ( ; j != 100; ++j )
...

This statement might be used if j were already set to some initial value before the loop was entered.

A for loop that has its looping_condition field omitted effectively sets up an infinite loop; that is, a loop that is theoretically executed forever. Such a loop can be used provided there is some other means used to exit from the loop (such as executing a return, break, or gotostatement as discussed elsewhere in this book).

Declaring Variables

You can also declare variables as part of your initial expression inside a for loop. This is done using the normal ways you’ve defined variables in the past. For example, the following can be used to set up a for loop with an integer variable counter both defined and initialized to the value1:

for ( int counter = 1; counter <= 5; ++counter )

The variable counter is only known throughout the execution of the for loop and cannot be accessed outside the loop. As another example, the following for loop

for ( int n = 1, triangularNumber = 0; n <= 200; ++n )
triangularNumber += n;

defines two integer variables and sets their values accordingly.

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 (or statements)

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 theprogram statement.

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

Program 4.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 4.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 immediately 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_expression; loop_condition; loop_expression )
program statement (or statements)

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

init_expression;
while ( loop_condition ) {
program statement (or statements)
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 integers. For example, the gcdof 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 arbitrary 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 common 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 computer program. An analysis of the steps of the algorithm reveals that step 2 is repetitively executed as long as the value of vis not equal to 0. This realization leads to the natural implementation of this algorithm in C with the use of a while statement.

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

Program 4.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;
}


Program 4.7 Output


Please type in two nonnegative integers.
150 35
Their greatest common divisor is 5


Program 4.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 4.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 accomplishes 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 4.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 4.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.

The do Statement

The two looping statements discussed so far in this chapter both make a test of the conditions before the loop is executed. Therefore, the body of the loop might never be executed at all if the conditions are not satisfied. When developing programs, it sometimes becomes desirable to have the test made at the end of the loop rather than at the beginning. Naturally, the C language provides a special language construct to handle such a situation. This looping statement is known as the do statement. The syntax of this statement is as follows:

do
program statement (or statements)
while ( loop_expression );

Execution of the do statement proceeds as follows: the program statement is executed first. Next, the loop_expression inside the parentheses is evaluated. If the result of evaluating the loop_expression is TRUE, the loop continues and the program statement is once again executed. As long as evaluation of the loop_expression continues to be TRUE, the program statement is repeatedly executed. When evaluation of the expression proves FALSE, the loop is terminated, and the next statement in the program is executed in the normal sequential manner.

The do statement is simply a transposition of the while statement, with the looping conditions placed at the end of the loop rather than at the beginning.

Remember that, unlike the for and while loops, the do statement guarantees that the body of the loop is executed at least once.

In Program 4.8, you used a while statement to reverse the digits of a number. Go back to that program and try to determine what would happen if you typed in the number 0 instead of 13579. The loop of the while statement would never be executed, and you would simply end up with a blank line in your display (as a result of the display of the newline character from the second printf() statement). If you use a do statement instead of a while statement, you are assured that the program loop executes at least once, thus guaranteeing the display of at least one digit in all cases. Program 4.9 shows this revised program.

Program 4.9 Implementing a Revised Program to Reverse the Digits of a Number


// Program to reverse the digits of a number

#include <stdio.h>

int main ()
{
int number, right_digit;

printf ("Enter your number.\n");
scanf ("%i", &number);

do {
right_digit = number % 10;
printf ("%i", right_digit);
number = number / 10;
}
while ( number != 0 );

printf ("\n");

return 0;
}


Program 4.9 Output


Enter your number.
13579
97531


Program 4.9 Output (Rerun)


Enter your number.
0
0


As you can see from the program’s output, when 0 is keyed into the program, the program correctly displays the digit 0.

The break Statement

Sometimes when executing a loop, it becomes desirable to leave the loop as soon as a certain condition occurs (for instance, you detect an error condition, or you reach the end of your data prematurely). The break statement can be used for this purpose. Execution of the break statement causes the program to immediately exit from the loop it is executing, whether it’s a for, while, or do loop. Subsequent statements in the loop are skipped, and execution of the loop is terminated. Execution continues with whatever statement follows the loop.

If a break is executed from within a set of nested loops, only the innermost loop in which the break is executed is terminated.

The format of the break statement is simply the keyword break followed by a semicolon:

break;

The continue Statement

The continue statement is similar to the break statement except it doesn’t cause the loop to terminate. Rather, as its name implies, this statement causes the loop in which it is executed to be continued. At the point that the continue statement is executed, any statements in the loop that appear after the continue statement are automatically skipped. Execution of the loop otherwise continues as normal.

The continue statement is most often used to bypass a group of statements inside a loop based upon some condition, but to otherwise continue execution of the loop. The format of the continue statement is simply

continue;

Don’t use the break or continue statements until you become very familiar with writing program loops and gracefully exiting from them. These statements are too easy to abuse and can result in programs that are hard to follow.

Now that you are familiar with all the basic looping constructs provided by the C language, you are ready to learn about another class of language statements that enable you to make decisions during the execution of a program. These decision-making capabilities are described in detail inChapter 5, “Making Decisions.” First, try the exercises that follow to be certain you understand how to work with loops in C.

Exercises

1. Type in and run the nine programs presented in this chapter. Compare the output produced by each program with the output presented after each program in the text.

2. Write a program to generate and display a table of n and n2, for integer values of n ranging from 1 to 10. Be certain to print appropriate column headings.

3. A triangular number can also be generated by the formula

triangularNumber = n (n + 1) / 2

for any integer value of n. For example, the 10th triangular number, 55, can be generated by substituting 10 as the value for n in the preceding formula. Write a program that generates a table of triangular numbers using the preceding formula. Have the program generate every fifth triangular number between 5 and 50 (that is, 5, 10, 15, ..., 50).

4. The factorial of an integer n, written n!, is the product of the consecutive integers 1 through n. For example, 5 factorial is calculated as

5! = 5 x 4 x 3 x 2 x 1 = 120

Write a program to generate and print a table of the first 10 factorials.

5. The following perfectly valid C program was written without much attention paid to its format. As you will observe, the program is not very readable. (And believe it or not, it is even possible to make this program significantly more unreadable!) Using the programs presented in this chapter as examples, reformat the program so that it is more readable. Then type the program into the computer and run it.

#include <stdio.h>
int main(void){
int n,two_to_the_n;
printf("TABLE OF POWERS OF TWO\n\n");
printf(" n 2 to the n\n");
printf("--- ---------------\n");
two_to_the_n=1;
for(n=0;n<=10;++n){
printf("%2i %i\n",n,two_to_the_n); two_to_the_n*=2;}
return 0;}

6. A minus sign placed in front of a field width specification causes the field to be displayed left-justified. Substitute the following printf() statement for the corresponding statement in Program 4.2, run the program, and compare the outputs produced by both programs.

printf ("%-2i %i\n", n, triangularNumber);

7. A decimal point before the field width specification in a printf() statement has a special purpose. Try to determine its purpose by typing in and running the following program. Experiment by typing in different values each time you are prompted.

#include <stdio.h>

int main (void)
{
int dollars, cents, count;

for ( count = 1; count <= 10; ++count ) {
printf ("Enter dollars: ");
scanf ("%i", &dollars);
printf ("Enter cents: ");
scanf ("%i", &cents);
printf ("$%i.%.2i\n\n", dollars, cents);
}
return 0;
}

8. Program 4.5 allows the user to type in only five different numbers. Modify that program so that the user can type in the number of triangular numbers to be calculated.

9. Rewrite Programs 4.2 through 4.5, replacing all uses of the for statement with equivalent while statements. Run each program to verify that both versions are identical.

10. What would happen if you typed a negative number into Program 4.8? Try it and see.

11. Write a program that calculates the sum of the digits of an integer. For example, the sum of the digits of the number 2155 is 2 + 1 + 5 + 5 or 13. The program should accept any arbitrary integer typed in by the user.