The forStatement 53
Nested forLoops
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 forstatement can be used to set up
such a loop. Program 5.5 and its associated output illustrate this technique.
Program 5.5 Using Nested forLoops
#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