An Initial Example

I l @ ve RuBoard

An Initial Example

You are already somewhat familiar with the while loop, but let's review it with a program (see Listing 6.1) that sums integers entered from the keyboard. This example makes use of the return value of scanf() to terminate input.

Listing 6.1 The summing.c program.
 /* summing.c -- sums integers entered interactively */ #include <stdio.h> int main(void) {   long num;   long sum = 0L;        /* initialize sum to zero     */   int status;   printf("Please enter an integer to be summed. ");   printf("Enter q to quit.\n");   status = scanf("%ld", &num);   while (status == 1)   /* == means "is equal to"     */   {         sum = sum + num;         printf("Please enter next integer to be summed. ");         printf("Enter q to quit.\n");         status = scanf("%ld", &num);   }   printf("Those integers sum to %ld.\n", sum);   return 0; } 

Listing 6.1 uses type long to allow for larger numbers . For consistency, you initialize sum to 0L (type long zero) rather than to (type int zero), even though C's automatic conversions enable you to use a plain .

Here is a sample run:

 Please enter an integer to be summed. Enter q to quit.  20  Please enter next integer to be summed. Enter q to quit.  5  Please enter next integer to be summed. Enter q to quit.  30  Please enter next integer to be summed. Enter q to quit.  q  Those integers sum to 55. 

Program Comments

Because you are reviewing the while loop, let's look at it first. The test condition for this loop is the following expression:

 status == 1 

The == operator is C's equality operator ; that is, this expression tests whether status is equal to 1 . Don't confuse it with status = 1 , which assigns 1 to status . With the status == 1 test condition, the loop repeats as long as status is 1 . For each cycle, the loop adds the current value of num to sum , so that sum maintains a running total. When status gets a value other than 1 , the loop terminates, and the program reports the final value of sum .

For the program to work properly, it should get a new value for num on each loop cycle, and it should reset status on each cycle. The program accomplishes this by using two distinct features of scanf() . First, it uses scanf() to attempt to read a new value for num . Second, it uses the scanf() return value to report on the success of that attempt. Recall from Chapter 4, "Character Strings and Formatted Input/Output," that scanf() returns the number of items successfully read. If scanf() succeeds in reading an integer, it places the integer into num and returns the value 1 , which is assigned to status . (Note that the input value goes to num , not to status .) This updates both num and the value of status , and the while loop goes through another cycle. If you respond with non-numeric input, such as q , scanf() fails to find an integer to read, so its return value and status will be . That terminates the loop. The input character q , by the way, because it wasn't a number, is placed back into the input queue; it does not get read. (Actually, any non-numeric input, not just q , terminates the loop, but asking the user to enter a q is a simpler instruction than asking the user to enter non-numeric input.)

This dual use of scanf() gets around a troublesome aspect of interactive input to a loop: How do you tell the loop when to stop? Suppose, for instance, that scanf() did not have a return value. Then the only thing that would change on each loop is the value of num . You could use the value of num to terminate the loop, using, say, num > 0 ( num greater than ) or num ! = 0 ( num not equal to ) as a test condition, but this prevents you from entering certain values, such as -3 or , as input. Instead, you could add new code to the loop, such as asking "Do you wish to continue? <y/n>" at each cycle and then testing to see whether the user entered a y . This is a bit clunky and slows down input. Using the return value of scanf() avoids these problems.

Now let's take a closer look at the program structure. You can summarize it as follows :

 initialize sum to 0 prompt user read input while the input is an integer,      add the input to sum,      prompt user,      then read next input after input completes, print sum 

This, incidentally, is an example of pseudocode , which is the art of expressing a program in simple English that parallels the forms of a computer language. Pseudocode is useful for working out the logic of a program. After the logic seems right, you can translate the pseudocode to the actual programming code. One advantage of pseudocode is that it enables you to concentrate on the logic and organization of a program and spares you from simultaneously worrying about how to express the ideas in a computer language. Here, for example, you can use indentation to indicate a block of code and not worry about C syntax requiring braces. Another advantage is that pseudocode is not tied to a particular language, so the same pseudocode can be translated into different computer languages.

Anyway, because the while loop is an entry-condition loop, the program must get the input and check the value of status before it goes to the body of the loop. That is why you have a scanf() before the while . For the loop to continue, you need a read statement inside the loop so that it can find out the status of the next input. That is why you also have a scanf() statement at the end of the while loop; it readies the loop for its next iteration. You can think of the following as a standard format for a loop:

 get first value to be tested while the test is successful      process value      get next value 

C-Style Reading Loop

Listing 6.1 could be written in Pascal or BASIC or FORTRAN along the same design displayed in the pseudocode. C, however, offers a shortcut. The construction

 status = scanf("%ld", #); while (status == 1) {         /* loop actions */         status = scanf("%ld", &num); can be replaced by the following: while (scanf("%ld", &num) == 1) {         /* loop actions */ } 

The second form uses scanf() in two different ways simultaneously. First, the function call, if successful, places a value in num . Second, the function's return value (which is 1 or and not the value of num ) controls the loop. Because the loop condition is tested at each iteration, scanf() is called at each iteration, providing a new num and a new test. In other words, C's syntax features let you replace the standard loop format with the following condensed version:

 while getting and testing the value succeeds     process the value 

Now let's take a more formal look at the while statement.

I l @ ve RuBoard


C++ Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 314
Authors: Stephen Prata

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net