Loops

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

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.

For

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);
}

Exercises

  1. Write a guess my number game. The user will guess a number, the program then tells them if they are too high or too low. The program runs until the user guesses the number. Look up the rand() function to find out how to generate an initial number.
  2. Write the classic FizzBuzz program. For the numbers from 1 to 100, if the number is divisible by 3, print out 'Fizz'. If the number is divisible by 5, print out 'Buzz'. If the number is divisible by both 3 and 5, print out 'FizzBuzz'.