20.09.2015 Views

Programming in C

Kochan - ProgramminginC

Kochan - ProgramminginC

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

44 Chapter 5 Program Loop<strong>in</strong>g<br />

Program 5.1<br />

Cont<strong>in</strong>ued<br />

<strong>in</strong>t ma<strong>in</strong> (void)<br />

{<br />

<strong>in</strong>t triangularNumber;<br />

triangularNumber = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8;<br />

pr<strong>in</strong>tf ("The eighth triangular number is %i\n",<br />

triangularNumber);<br />

}<br />

return 0;<br />

Program 5.1 Output<br />

The eighth triangular number is 36<br />

One of the fundamental properties of a computer is its ability to repetitively execute a<br />

set of statements.These loop<strong>in</strong>g capabilities enable you to develop concise programs conta<strong>in</strong><strong>in</strong>g<br />

repetitive processes that could otherwise require thousands or even millions of<br />

program statements to perform.The C programm<strong>in</strong>g language conta<strong>in</strong>s three different<br />

program statements for program loop<strong>in</strong>g.They are known as the for statement, the<br />

while statement, and the do statement. Each of these statements are described <strong>in</strong> detail<br />

<strong>in</strong> this chapter.<br />

The for Statement<br />

Let’s dive right <strong>in</strong> and take a look at a program that uses the for statement.The purpose<br />

of Program 5.2 is to calculate the 200th triangular number. See if you can determ<strong>in</strong>e<br />

how the for statement works.<br />

Program 5.2 Calculat<strong>in</strong>g the 200th Triangular Number<br />

/* Program to calculate the 200th triangular number<br />

Introduction of the for statement */<br />

#<strong>in</strong>clude <br />

<strong>in</strong>t ma<strong>in</strong> (void)<br />

{<br />

<strong>in</strong>t n, triangularNumber;<br />

triangularNumber = 0;

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!