Programming in C

(Barry) #1

5Program Looping


5 Program Looping

IFYOU ARRANGE 15 DOTSin 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 nrows 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>

Free download pdf