5. Program Looping

In objective-C you can repeatedly execute a sequence of code in several ways. These looping capabilities are the subject of this chapter, and they consist of the following:

• The for statement

• The while statement

• The do statement

We'll start with a simple example: counting numbers.

If you were to arrange 15 marbles into the shape of a triangle, you would end up with an arrangement that might look something like this:

image

The first row of the triangle contains one marble, the second row contains two marbles, and so on. In general, the number of marbles required to form a triangle containing n rows would be the sum of the integers from 1 through n. This sum is known as a triangular number.

If you started at 1, the fourth triangular number would be the sum of the consecutive integers 1–4 (1 + 2 + 3 + 4), or 10.

Suppose you wanted to write a program that calculated and displayed 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, let's assume you wanted to write a program in Objective-C to perform this task. Such a program is shown in Program 5.1.

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

Program 5.1.


#import <stdio.h>

// Program to calculate the eighth triangular number

int main (int argc, char *argv[])
{
  int triangularNumber;

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

  printf ("The eighth triangular number is %i ", triangularNumber);
return 0;
}


Program 5.1. Output


The eighth triangular number is 36


One of the fundamental properties of a computer is its capability to repetitively execute a set of statements. These looping capabilities enable programmers to develop concise programs containing repetitive processes that could otherwise require thousands or even millions of program statements to perform. The Objective-C language contains three program statements for program looping.

The for Statement

Let's take a look at a program that uses the for statement. The purpose of Program 5.2 is to calculate the 200th triangular number. See whether you can determine how the for statement works.

Program 5.2.


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


#import <stdio.h>

int main (int argc, char *argv[])
{
    int n, triangularNumber;

  triangularNumber = 0;

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

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

  return 0;
}


Program 5.2. Output


The 200th triangular number is 20100


Some explanation is owed for Program 5.2. The method employed to calculate the 200th triangular number is really the same as that used to calculate the 8th triangular number in the previous program—the integers from 1 to 200 are summed.

The variable triangularNumber is set equal to 0 before the for statement is reached. In general, you need to initialize all variables to some value (just like your objects) before you use them in your program. As you'll learn later, certain types of variables are given default initial values, but you should set them anyway.

The for statement provides the mechanism that enables you to avoid having to explicitly write 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

The three expressions 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 Objective-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 5.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 specifies the condition(s) necessary for the loop to continue. In other words, looping continues as long as this condition is satisfied. Once again referring to Program 5.2, the loop_condition of the for 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 Objective-C programming language. These operators are used to test specific conditions. The answer to the test is yes (or TRUE) if the condition is satisfied and no (or FALSE) if the condition is not satisfied.

Table 5.1 lists all the relational operators available in Objective-C.

Table 5.1. Relational Operators

image

The relational operators have lower precedence than all arithmetic operators. This means, for example, that an expression such as

a < b + c

is evaluated as

a < (b + c)

This is 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 whether 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 depends on the particular test being made and in some instances on your particular preferences. For example, the relational expression

n <= 200

can be equivalently expressed as

n < 201

Returning to the previous example, the program statement that forms the body of the for loop—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 n to the value of triangularNumber.

When the loop_condition is no longer satisfied, execution of the program continues with the program statement immediately following the for loop. In this 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 5.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 it ranges in value from 1 through 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 is 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. 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 1 to it or subtracting 1 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 executed one time. Also, remember not to put a semicolon after the closed parenthesis at the end of the loop because this will immediately end the loop.

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

Program 5.3.


// Program to generate a table of triangular numbers

#import <stdio.h>

int main (int argc, char *argv[])
{
    int n, triangularNumber;

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

  triangularNumber = 0;

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

  return 0;
}


Program 5.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


In Program 5.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 first printf 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 calculates the first 10 triangular numbers. The variable n is used to count the current number whose sum from 1 to n you are computing, and 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. As mentioned earlier, 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 Objective-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 5.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. At a quick glance, you can easily 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, triangularNumber);
}

Here, the opening brace is placed on the line following 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. 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. Surely, you must have made a typographical mistake and meant to insert n = n + 1 instead of this funny-looking expression:

++n

The fact of the matter is that ++n is actually a perfectly valid Objective-C expression. It introduces a new (and rather unique) operator in the Objective-C programming language—the increment operator. The function of the double plus sign, or the increment operator, is to add 1 to its operand. Addition by 1 is such a common operation in programs that a special operator was created solely for this purpose. Therefore, the expression ++n is equivalent to the expression n = n + 1. At first glance it might appear that n = n + 1 is more readable, but you will soon get used to the function of this operator and even learn to appreciate its succinctness.

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

bean_counter = bean_counter – 1

can be equivalently expressed using the decrement operator, like so:

--bean_counter

Some programmers prefer to put the ++ or -- after the variable name, as in n++ or bean_counter--. This is acceptable and is a matter of personal preference.

You might have noticed that the last line of output from Program 5.3 doesn't line up. This minor annoyance can be corrected by substituting the following printf statement in place of the corresponding statement from Program 5.3.

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

To verify that this change solves the problem, here is the output from the modified program (called Program 5.3A).

Program 5.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 is 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 also that the size of the integer to be displayed should take up two columns in the display. Any integer that would normally take up less than two columns (that is, the integers 0–9) will be 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 will be used for displaying the value of n; you also ensure that the values of triangularNumber will be aligned.

If the value 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.

Terminal Input

Program 5.2 calculates the 200th triangular number, and nothing more. What if you wanted to calculate the 50th or the 100th triangular number instead? Well, if that were the case, you would have to change the program so that the for loop would be executed the correct number of times. You would also have to change the printf statement to display the correct message.

An easier solution might be to somehow have the program ask you which triangular number you wanted to calculate. Then, after you had given your answer, the program could calculate the desired triangular number. Such a solution can be effected by using a routine called scanf. The scanf routine is similar in concept to the printf routine. Whereas the printf routine is used to display values at the terminal, the purpose of the scanf routine is to enable the programmer to type values into the program. Program 5.4 asks the user which triangular number should be calculated, calculates that number, and then displays the results.

Program 5.4.


#import <stdio.h>

int main (int argc, char *argv[])
{
    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 ", number, triangularNumber);

     return 0;
}


In the program output that follows, the number typed in by the user (100) is set in bolder type to distinguish it from the output displayed by the program.

Program 5.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 calculated the 100th triangular number and displayed the result of 5050 at the terminal. The user could have just as easily typed in the number 10, or 30, if he wanted to calculate those particular triangular numbers.

The first printf statement in Program 5.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, which is 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. We will discuss this character, which is actually an operator, in great detail when we talk about pointers in Chapter 13.

Given the preceding discussion, you can now see that the scanf call from Program 5.4 specifies that an integer value is to be read from the terminal and stored into the variable number. This value represents the particular triangular number the user wants to have calculated.

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

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

Nested for Loops

Program 5.4 gives the user the flexibility to have the program calculate any triangular number that is desired. But suppose the user had a list of five triangular numbers to be calculated? In such a case, the user could simply execute the program five times, each time typing in the next triangular number from the list to be calculated.

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

Program 5.5.


#import <stdio.h>

int main (int argc, char *argv[])
{
  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 ", number, triangularNumber);

   }

  return 0;
}


Program 5.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 is as follows:

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

This 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. You might be able to more easily 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 results.
}

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, a for statement is actually contained within another for statement. This is perfectly valid in Objective-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. At a quick glance, you can easily determine which statements are contained within each for statement.

for Loop Variants

Before leaving this discussion of the for loop, we should mention some of the syntactic variations that are permitted in forming this 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 perhaps more than one expression that you want evaluated each time through the loop. You can include multiple expressions in any of the fields of the for loop, provided 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 -= 10 )
...

sets up two index variables: i and j, which initialize to 0 and 100, respectively, before the loop begins. Each time after the body of the loop is executed, the value of i is incremented by 1 and the value of j is decremented by 10.

Just as you might need to include more than one expression in a particular field of the for statement, you also might need 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 no initial expression 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, like so:

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 theoretically will be executed forever. Such a loop can be used as long as some other means is used to exit from the loop (such as executing a return, break, or goto statement, as discussed later in this book).

You can also define variables as part of your initial expression inside a for loop1. This is done using the typical ways in which we'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 value 1, like so:

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

The variable counter is only known throughout the execution of the for loop (it's called a local variable) and cannot be accessed outside the loop. As another example, the for loop

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

defines two integer variables and sets their values accordingly.

The while Statement

The while statement further extends the Objective-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), expression is again evaluated. If the result of the evaluation is TRUE, the program statement is again executed. This process continues until expression finally evaluates FALSE, at which point the loop is terminated. Execution of the program then continues with the statement that follows program statement.

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

Program 5.6.


// This program introduces the while statement

#import <stdio.h>

int main (int argc, char *argv[])
{
   int count = 1;

   while ( count <= 5 ) {
         printf ("%i ", 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 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 see that this loop is executed five times or until the value of count reaches 5.

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

can be equivalently expressed in the form of a while statement, like so:

init_expression;
while ( loop_condition )
{
     program statement
     loop_expression;
}

When 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 (we'll abbreviate it hereafter as gcd) of two integers is the largest integer value that evenly divides the two integers. For example, the gcd of 10 and 15 is 5 because 5 is the largest integer that evenly divides both 10 and 15.

A procedure, or algorithm, that can be followed to arrive at the gcd of two arbitrary integers is based on a procedure originally developed by Euclid around 300 B.C. It 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 we 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 previous algorithm works—simply take it on faith. We are more concerned here with developing a program to find the greatest common divisor than in 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, developing the computer program becomes a much simpler task. 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 Objective-C with the use of a while statement.

The following program finds the gcd of two nonnegative integer values typed in by the user.

Program 5.7.


// This program finds the greatest common divisor
// of two nonnegative integer values

#import <stdio.h>

int main (int argc, char *argv[])
{
   unsigned int u, v, temp;

   printf ("Please type in two nonnegative integers. ");
   scanf ("%u%u", &u, &v);

   while ( v != 0 ) {
         temp = u % v;
         u = v;
         v = temp;
   }

   printf ("Their greatest common divisor is %u ", u);
   return 0;
}


Program 5.7. Output


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 540
Their greatest common divisor is 27


After the two integer values have been entered and stored into the variables u and v (using the %u format characters to read in an unsigned integer value), 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 of the original value of u, is displayed at the terminal with an appropriate message.

You will use the algorithm for finding the greatest common divisor again in Chapter 7, “More on Classes,” when you return to working with fractions.

For the next program that illustrates the use of the while statement, let's consider 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, the program should 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 one's own method for solving the problem leads to the development of an algorithm. For the task of reversing the digits of a number, the 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 that the modulus operator 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 you 3, which is the next digit of the 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.


// Program to reverse the digits of a number

#import <stdio.h>

int main (int argc, char *argv[])
{
  int number, right_digit;

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

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

  printf (" ");
  return 0;
}


Program 5.8. Output


Enter your number.
13579
97531


Each digit is displayed as it is extracted by the program. Notice that a newline character is not included 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 constructs discussed thus 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, you sometimes might want to have the test made at the end of the loop rather than at the beginning. Naturally, the Objective-C language provides a special language construct to handle such a situation, known as the do statement. The syntax of this statement is as follows:

do
  program statement
while ( expression );

Execution of the do statement proceeds as follows: program statement is executed first. Next, the expression inside the parentheses is evaluated. If the result of evaluating expression is TRUE, the loop continues and program statement is again executed. As long as the evaluation of expression continues to be TRUE, program statement is repeatedly executed. When the 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.

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

Program 5.9.


// Program to reverse the digits of a number

#import <stdio.h>

int main (int argc, char *argv[])
{
  int number, right_digit;

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

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

  printf (" ");

  return 0;
}


Program 5.9. Output


Enter your number.
13579
97531


Program 5.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, you'll want to leave the loop as soon as a certain condition occurs (for instance, maybe you detect an error condition or 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, like so:

break;

The continue Statement

The continue statement is similar to the break statement except it doesn't cause the loop to terminate. At the point that the continue statement is executed, any statements that appear after the continue statement up to the end of the loop are 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 on some condition, but to otherwise continue execution of the loop. The format of the continue statement is as follows:

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 Objective-C language, you're ready to learn about another class of language statements that enables you to make decisions during the execution of a program. These decision-making capabilities are described in detail in the next chapter.

Exercises

  1. Write a program to generate and display a table of n and n2, for integer values of n ranging from 1 through 10. Be sure to print the appropriate column headings.
  2. A triangular number can also be generated for any integer value of n by this formula:

    Triangular number = n (n + 1) / 2

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

  3. 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 follows:

    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.

  4. 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 5.2, run the program, and compare the outputs produced by both programs:

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

  5. Program 5.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.
  6. Rewrite Programs 5.25.5, replacing all uses of the for statement with equivalent while statements. Run each program to verify that both versions are identical.
  7. What would happen if you typed a negative number into Program 5.8? Try it and see.
  8. 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.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.198.81