Programming in C

(Barry) #1

44 Chapter 5 Program Looping


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 loopingcapabilities 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 forstatement, the
whilestatement, and the dostatement. Each of these statements are described in detail
in this chapter.

The forStatement


Let’s dive right in and take a look at a program that uses the forstatement.The purpose
of Program 5.2 is to calculate the 200th triangular number. See if you can determine
how the forstatement works.

Program 5.2 Calculating the 200th Triangular Number
/* Program to calculate the 200th triangular number
Introduction of the for statement */

#include <stdio.h>

int main (void)
{
int n, triangularNumber;

triangularNumber = 0;

Program 5.1 Continued
Free download pdf