8
Loops

In Xcode, create yet another new project: a C Command Line Tool named Coolness.

The first program I ever wrote printed the words, Aaron is Cool. (I was 10 at the time.) Write a program to do that now:

#​i​n​c​l​u​d​e​ ​<​s​t​d​i​o​.​h​>​

i​n​t​ ​m​a​i​n​(​i​n​t​ ​a​r​g​c​,​ ​c​o​n​s​t​ ​c​h​a​r​ ​*​ ​a​r​g​v​[​]​)​
{​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​A​a​r​o​n​ ​i​s​ ​C​o​o​l​​n​"​)​;​
 ​ ​ ​ ​r​e​t​u​r​n​ ​0​;​
}​

Build and run the program.

Let’s suppose for a moment that you could make my 10-year-old self feel more confident if the program printed the affirmation a dozen times. How would you do that?

Here is the dumb way:

#​i​n​c​l​u​d​e​ ​<​s​t​d​i​o​.​h​>​

i​n​t​ ​m​a​i​n​(​i​n​t​ ​a​r​g​c​,​ ​c​o​n​s​t​ ​c​h​a​r​ ​*​ ​a​r​g​v​[​]​)​
{​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​A​a​r​o​n​ ​i​s​ ​C​o​o​l​​n​"​)​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​A​a​r​o​n​ ​i​s​ ​C​o​o​l​​n​"​)​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​A​a​r​o​n​ ​i​s​ ​C​o​o​l​​n​"​)​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​A​a​r​o​n​ ​i​s​ ​C​o​o​l​​n​"​)​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​A​a​r​o​n​ ​i​s​ ​C​o​o​l​​n​"​)​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​A​a​r​o​n​ ​i​s​ ​C​o​o​l​​n​"​)​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​A​a​r​o​n​ ​i​s​ ​C​o​o​l​​n​"​)​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​A​a​r​o​n​ ​i​s​ ​C​o​o​l​​n​"​)​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​A​a​r​o​n​ ​i​s​ ​C​o​o​l​​n​"​)​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​A​a​r​o​n​ ​i​s​ ​C​o​o​l​​n​"​)​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​A​a​r​o​n​ ​i​s​ ​C​o​o​l​​n​"​)​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​A​a​r​o​n​ ​i​s​ ​C​o​o​l​​n​"​)​;​

 ​ ​ ​ ​r​e​t​u​r​n​ ​0​;​
}​

The smart way is to create a loop.

The while loop

The first loop you will use is a while loop. The while construct works something like the if construct discussed in Chapter 4. You give it an expression and a block of code contained by curly braces. In the if construct, if the expression is true, the block of code is run once. In the while construct, the block is run again and again until the expression becomes false.

Rewrite the main() function to look like this:

#​i​n​c​l​u​d​e​ ​<​s​t​d​i​o​.​h​>​

i​n​t​ ​m​a​i​n​(​i​n​t​ ​a​r​g​c​,​ ​c​o​n​s​t​ ​c​h​a​r​ ​*​ ​a​r​g​v​[​]​)​
{​
 ​ ​ ​ ​i​n​t​ ​i​ ​=​ ​0​;​
 ​ ​ ​ ​w​h​i​l​e​ ​(​i​ ​<​ ​1​2​)​ ​{​
 ​ ​ ​ ​ ​ ​ ​ ​p​r​i​n​t​f​(​"​%​d​.​ ​A​a​r​o​n​ ​i​s​ ​C​o​o​l​​n​"​,​ ​i​)​;​
 ​ ​ ​ ​ ​ ​ ​ ​i​+​+​;​
 ​ ​ ​ ​}​
 ​ ​ ​ ​r​e​t​u​r​n​ ​0​;​
}​

Build and run the program.

The conditional (i < 12) is being checked before each execution of the block. The first time it evaluates to false, execution leaps to the code after the block.

Notice that the second line of the block increments i. This is important. If i was not incremented, then this loop, as written, would continue forever because the expression would always be true.

Here is a flow-chart of this while loop:

The while loop
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset