The for loop

The while loop is a general looping structure, but C programmers use the same basic pattern a lot:

s​o​m​e​ ​i​n​i​t​i​a​l​i​z​a​t​i​o​n​
w​h​i​l​e​ ​(​s​o​m​e​ ​c​h​e​c​k​)​ ​{​
 ​ ​ ​ ​s​o​m​e​ ​c​o​d​e​
 ​ ​ ​ ​s​o​m​e​ ​l​a​s​t​ ​s​t​e​p​
}​

So, the C language has a shortcut: the for loop. In the for loop, the pattern shown above becomes:

f​o​r​ ​(​s​o​m​e​ ​i​n​i​t​i​a​l​i​z​a​t​i​o​n​;​ ​s​o​m​e​ ​c​h​e​c​k​;​ ​s​o​m​e​ ​l​a​s​t​ ​s​t​e​p​)​ ​{​
 ​ ​ ​ ​s​o​m​e​ ​c​o​d​e​;​
}​

Change the program to use a for loop:

#​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​[​]​)​
{​
 ​ ​ ​ ​f​o​r​ ​(​i​n​t​ ​i​ ​=​ ​0​;​ ​i​ ​<​ ​1​2​;​ ​i​+​+​)​ ​{​
 ​ ​ ​ ​ ​ ​ ​ ​p​r​i​n​t​f​(​"​%​d​.​ ​A​a​r​o​n​ ​i​s​ ​C​o​o​l​​n​"​,​ ​i​)​;​
 ​ ​ ​ ​}​
 ​ ​ ​ ​r​e​t​u​r​n​ ​0​;​
}​

Figure 7.2  for loop

for loop

Note that in this simple loop example, you used the loop to dictate the number of times something happens. More commonly, however, loops are used to iterate through a collection of items, such as a list of names. For instance, I could modify this program to use a loop in conjunction with a list of friends’ names. Each time through the loop, a different friend would get to be cool. We’ll see more of collections and loops starting in Chapter 15.

..................Content has been hidden....................

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