Programming in C

(Barry) #1
The forStatement 47

When the loop_conditionis no longer satisfied, execution of the program continues
with the program statement immediately following the forloop. In your program, exe-
cution continues with the printfstatement after the loop has terminated.
The final component of the forstatement contains an expression that is evaluated
each time afterthe body of the loop is executed. In Program 5.2, this loop_expression
adds 1 to the value of n.Therefore, the value of nis incremented by 1 each time after its
value has been added into the value of triangularNumberand ranges in value from 1 to
201.
It is worth noting that the last value that nattains, namely 201 , is notadded into the
val ue of triangularNumberbecause the loop is terminated as soon asthe looping condi-
tion is no longer satisfied, or as soon as nequals 201.
In summary, execution of the forstatement 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 indexvariable, 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;

Free download pdf