1.10. Implementing Loops with For Statements
Problem
You want to implement a code that repeats a certain number of times, perhaps applying the same procedure to every element in an array or some other changing values.
Solution
Use the for statement. The format of this statement is:
for (<replaceable>code to execute before loop</replaceable>;
<replaceable>condition to be met for the loop to terminate</replaceable>;
<replaceable>code to execute in every iteration of the loop</replaceable>){
}Note
All three clauses of the for loop are optional. In other words, you can have a for loop that looks like this:
for (;;){ YOUR CODE HERE }This is known as an infinite-loop or a loop that has no condition to terminate and will run forever. This is a very bad programming practice indeed and you should avoid using it by all means while developing iOS programs.
Discussion
Loops are useful in programming because you will often need to start a loop from one place to another, from one index to another, or from start to stop. For instance, you might want to loop through all characters inside a string and count how many “A” characters you can find in it. Another example is a loop that finds all files in a directory. This is a loop that finds the number of files and then starts from the first one until it gets to the last one.
Usually, programmers require a counter in their loops. For instance, you might want to read all the characters inside a C-String. For this, you will need the index of each character. If ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access