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​+​+​)​ ​{​ ​ ​ ​ ​ ​ ...

Get Objective-C Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.