Program Looping in C: The for Statement

Let’s dive right in and 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 if you can determine how the for statement works.

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

Program 5.2   Continued

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

triangularNumber = triangularNumber + n;

printf (“The 200th triangular number is %i\n”, 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 Program 5.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

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 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 the condition or conditions that are necessary for the loop to continue. In other words, looping continues as long as this con- dition is satisfied. Once again referring to Program 5.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.

1. Relational Operators

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

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, the relational expression

n <= 200

can be equivalently  expressed as

n < 201

Returning to our example, 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 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 your program, exe- cution 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 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 condi- tion 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 ini- tial 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 pro- gram 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 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 5.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 num- bers. Program 5.3 performs precisely this task!

Program 5.3   Generating a Table of Triangular Numbers

// Program to generate a table of triangular numbers

#include <stdio.h>

int main (void)

{

int n, triangularNumber;

Program 5.3   Continued

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 5.3   Output

It is always a good idea to add some extra printf statements to a program to provide more meaning to the output. In Program 5.3, the purpose of the first three printf state- ments 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 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 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. 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 pre- vious triangular number. This time, the “plus equals” operator is used, which was intro- duced in Chapter 4, “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 val- ues 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 eval- uated 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 expres- sion 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 appreci- ate 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 acceptable, and is a matter of personal preference.

2. Aligning  Output

One slightly disturbing thing that you might have noticed in Program 5.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 previ- ous 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 5.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 5.3A).

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 dis- play 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.

3. Program Input

Program 5.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 the printf statement to display the correct message.

An easier solution might be if you could somehow have the program ask which tri-angular 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 called scanf. 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 5.4 asks the user which triangular number should be calculated, proceeds to calculate that number, and then displays the results.

Program 5.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 5.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 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 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 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 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 11, “Pointers,” discusses this character, which is actually an operator, in great detail. Always remember to put the lead- ing & 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 5.4 specifies that an integer value is to be read from the terminal and stored in the vari- able 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 key- board pressed to signal that typing of the number is completed), the program then pro- ceeds to calculate 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.

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

4. Nested for Loops

Program 5.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 5.5 and its associated output illustrate this technique.

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

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 indi- cated 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 up to 127 levels!

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.)

5. 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 initial- ize before the loop begins or more than one expression that you want to evaluate each time through the loop.

5.1. 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.

5.2. 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 semi- colon. 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 semi- colon 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 infi- nite 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 goto statement as discussed  elsewhere in this book).

5.3. 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 fol- lowing can be used to set up a for loop with an integer variable counter both defined and initialized to the value 1:

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 following for loop

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

triangularNumber += n;

defines two integer variables and sets their values accordingly.

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 *