Computers were invented to perform repetative tasks, so we need tools to make performing the same action over and over again easy. There are two main looping constructs for this task: while and for loops.
while loops are useful when the loop will be performed an unknown
number of times, instead terminating when some condition is met.
while (condition) {
// Perform this task until condition is false
}
It is important to make sure that the body of the loop will eventually cause the condition to be false, otherwise your program can run forever.
Often we want to perform an action a known number of times. This can be done with a while loop as such.
int i = 0; // Initial the loop variable
while (i < 10) { // Loop terminiation condition
NSLog(@"Totally doing some useful work in the loop");
++i; // Increment the loop value
}
While this works, notice that the three pieces of information
necessary to loop are not grouped together. This can cause tricky
bugs. As the body of the loop gets larger and other functions are
called, the situation gets worse. for loops move these
three actions to the same place in your code
for (int i = 0; i < 10; ++i) { // Loop variable is declared, initialized, tested,
// and incremented in the same spot.
NSLog(@"Totally doing some useful work in the loop");
}
We have access to the counting variable inside of the loop. This can be used, for example, to print out the numbers between 1 and 10.
for (int i = 1; i <= 10; ++i) {
NSLog(@"The number is: %d", i);
}