Programming in C

(Barry) #1

48 Chapter 5 Program Looping


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

It is always a good idea to add some extra printfstatements to a program to provide
more meaning to the output. In Program 5.3, the purpose of the first three printfstate-
ments is simply to provide a general heading and to label the columns of the output.
Notice that the first printfstatement 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 nis used to count the current number
whose “sum from 1 to n"you are computing, whereas the variable triangularNumberis
used to store the value of triangular number n.
Execution of the forstatement commences by setting the value of the variable nto
1. Remember that the program statement immediately following the forstatement

Program 5.3 Continued
Free download pdf