IF YOU ARRANGE 15 DOTS in the shape of a triangle, you end up with an arrangement that might look something like this:
The first row of the triangle contains one dot, the second row contains two dots, and so on. In general, the number of dots it takes to form a triangle containing n rows is the sum of the integers from 1 through n. This sum is known as a triangular number. If you start at 1, the fourth triangular number is the sum of the consecutive integers 1 through 4 (1 + 2 + 3 + 4), or 10.
Suppose you want to write a program that calculates and displays the value of the eighth triangular number at the terminal. Obviously, you could easily calculate this num- ber in your head, but for the sake of argument, assume that you want to write a program in 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 happens if you need to find the value of the 200th triangular num- ber, for example? It certainly would be tedious to modify Program 5.1 to explicitly add up all of the integers from 1 to 200. Luckily, there is an easier way.
Program 5.1 Calculating the Eighth Triangular Number
// Program to calculate the eighth triangular number
#include <stdio.h>
int main (void)
{
int triangularNumber;
triangularNumber = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8;
printf (“The eighth triangular number is %i\n”, triangularNumber);
return 0;
}
Program 5.1 Output
The eighth triangular number is 36
One of the fundamental properties of a computer is its ability to repetitively execute a set of statements. These looping capabilities enable you to develop concise programs con- taining repetitive processes that could otherwise require thousands or even millions of program statements to perform. The C programming language contains three different program statements for program looping. They are known as the for statement, the while statement, and the do statement. Each of these statements are described in detail in this chapter.
Source: Kochan Stephen G. (2004), Programming in C: A Complete Introduction to the C Programming Language, Sams; Subsequent edition.