Iteration

Iteration, repetition, or looping, they all mean the same thing. When you want to repeat some portion of the program, you will use some form of iteration. Looping is a very common term to describe this. If programs didn't do some kind of iteration, they would all complete in a few seconds.

The while Statement

The most basic looping construct is the while statement. The form is identical to the if statement, but uses the keyword while instead. If you understand how the if statement works, it's easier to understand the while.
Single statementMultiple statements
(braces required)
if statement
while ( expression )
  statement
while ( expression )
{
  statements
}
if ( expression )
{
  statements
}

Whereas the if statement caused statement to be executed exactly once if expression was true, the while statement causes statement to be executed repeatedly as long as (a.k.a. while) expression remains true. If expression becomes false, then the repetition stops.

Another way to look at it is:

  1. If you want to execute something 0 or 1 time, use an if statement.
  2. If you want to execute something 0 or more times, use an while statement.
  3. If you want to execute something 1 or more times, use a do statement. (Later)
if       while       do
if ( expression )
  statement; // execute 0 or 1 time
      
while ( expression )
  statement; // execute 0 or more times
      
do 
  statement; // execute 1 or more times
while ( expression );

Simple example:

int count = 5;
int i = 0;

while (i < count)  /* controlling expression  */
  i++;             /* body of the loop        */
Example with output (and a review of expressions). Note that, like the if statement, the braces are only required with multiple (compound) statements:
Version #1 (braces required)Version #2 (braces optional)Version #3 (braces optional)
int count = 5;
int i = 0;

while (i < count)
{
  i++;
  printf("i is %i\n", i);
}
int count = 5;
int i = 0;

while (i < count)
{
  printf("i is %i\n", ++i);
}
int count = 5;
int i = 0;

while (i++ < count)
  printf("i is %i\n", i);

The output from all 3 examples: (Convince yourself that all 3 loops print the same thing.)
i is 1
i is 2
i is 3
i is 4
i is 5
Bart Simpson could have used C to make his punishment less painful:
int i = 1;
while (i <= 100)
{
  printf("I will check the CS 120 Style Guide before submitting code.\n");
  i++;
}
(Partial) output:


 I will check the CS 120 Style Guide before submitting code.
 I will check the CS 120 Style Guide before submitting code.
 I will check the CS 120 Style Guide before submitting code.
 I will check the CS 120 Style Guide before submitting code.
 I will check the CS 120 Style Guide before submitting code.
 I will check the CS 120 Style Guide before submitting code.
 I will check the CS 120 Style Guide before submitting code.
 I will check the CS 120 Style Guide before submitting code.
 I will check the CS 120 Style Guide before submitting code.
 I will check the CS 120 Style Guide before submitting code.
 I will check the CS 120 Style Guide before submitting code.
 I will check the CS 120 Style Guide before submitting code.
 I will check the CS 120 Style Guide before submitting code.
 I will check the CS 120 Style Guide before submitting code.
 I will check the CS 120 Style Guide before submitting code.
 I will check the CS 120 Style Guide before submitting code.
 I will check the CS 120 Style Guide before submitting code.
 I will check the CS 120 Style Guide before submitting code.
 I will check the CS 120 Style Guide before submitting code.
 I will check the CS 120 Style Guide before submitting code.
  





 
   
  
 
 

Notes:

Tip: If you are running your program from the command prompt and it is stuck in an infinite loop, pressing Ctrl-C will terminate the program.

The do Statement

Also sometimes referred to as the do...while statement. The basic format is:
Single statementMultiple statements
do 
  statement
while ( expression );
do
{ 
  statements
}
while ( expression );

The primary difference between the while statement and the do statement is that the body of the do statement is guaranteed to execute at least once. This is simply because the controlling expression is executed after the first iteration of the loop body:

Body executes 0 or more timesBody executes 1 or more times
while ( expression ) 
  statement
do 
  statement
while ( expression );

Example:

int number;
int choice;

do 
{
  printf("Enter a number: ");
  scanf("%d", &number);
  printf("You entered %i\n", number);

  printf("Enter another number? (1=yes,0=no) ");
  scanf("%d", &choice);
}
while (choice);
Sample run:
Enter a number: 23
You entered 23
Enter another number? (1=yes,0=no) 1
Enter a number: 10
You entered 10
Enter another number? (1=yes,0=no) 1
Enter a number: 5
You entered 5
Enter another number? (1=yes,0=no) 3
Enter a number: 12
You entered 12
Enter another number? (1=yes,0=no) 0
There really isn't much difference between while statement and the do statement. If you need the loop to execute at least once, then the do statement is the one to use.

In computer science, there are 3 general kinds of repetitions regarding the number of repetitions and the technique used:

RepetitionsKeyword
0 or 1 timeif
0 or more timeswhile
1 or more timesdo...while
Technically, the if isn't repeating anything. However, keep these keywords in mind when you have to do something in one of those three ways.

The for Statement

Now we get to the most complex of the looping mechanisms: the for statement. The general form is:
for ( expression1 ; expression2 ; expression3 )
  statement
and the compound version:
for ( expression1 ; expression2 ; expression3 )
{
  statements
}
The meaning of this is a little involved:
  1. First, evaluate expression1. This is executed and evaluated exactly once at the beginning of the loop.
  2. Evaluate expression2.
  3. If expression2 is true, execute statement. (If it's not true, jump out of the loop.)
  4. Evaluate expression3.
  5. Goto step 2.
This process can be written using an equivalent while statement:
expression1;
while ( expression2 )
{
  statements
  expression3;
}
In fact, we can re-write the while pseudocode for it:
  1. First, evaluate expression1. This is executed and evaluated exactly once at the beginning of the loop.
  2. While expression2 is true:
    1. Execute statement.
    2. Evaluate expression3.
This also means that any for loop can be written as a while loop and vice-versa.

Simple examples to print the numbers 1 through 10:
for loop #1for loop #2while loop
int i;
for (i = 1; i <= 10; i++)
  printf("%i\n", i);
int i;
for (i = 0; i < 10; i++)
  printf("%i\n", i + 1);
int i = 1;
while (i <= 10)
  printf("%i\n", i++);

The for loops above show the typical ways in which they are used. The variable i is sometimes called the loop control variable (or simply the counter) because it controls when the loop continues or stops. The three expressions generally do these things:

  1. expression1 - initializes the loop variable (counter)
  2. expression2 - compares the counter with some value (this is the condition)
  3. expression3 - modifies the counter (usually add or subtract 1)
Once the for loop gets going, it's repeatedly doing
[1]expression2
[2]statement
[3]expression3
[1]expression2
[2]statement
[3]expression3
[1]expression2
[2]statement
[3]expression3
. . .
[until expression2 is false]
for ( expression1 ; [1]expression2 ; [3]expression3 )
  [2]statement

These are just typical uses of the expressions. You can do practically anything with those expressions.

Count to 20 by 2Count down from 30 by 3Squares of 1 to 10
int i;
for (i = 2; i <= 20; i += 2)
  printf("%i\n", i);
  
2
4
6
8
10
12
14
16
18
20
int i;
for (i = 30; i >= 3; i -= 3)
  printf("%i\n", i);
  
30
27
24
21
18
15
12
9
6
3
  
int i;
for (i = 1; i <= 10; i++)
  printf("%i\n", i * i);
  
1
4
9
16
25
36
49
64
81
100
  

Of course, all of these could be written as while loops as well.
Count to 20 by 2Count down from 30 by 3Squares of 1 to 10
int i = 2;
while (i <= 20)
{
  printf("%i\n", i);
  i += 2;
}
int i = 30;
while (i >= 3)
{
  printf("%i\n", i);
  i -= 3;
}
int i = 1;
while (i <= 10)
{
  printf("%i\n", i * i); 
  i++;
}

More on Looping

Note that any or all of the expressions in the for loop can be omitted:

int i;
for (i = 1; i <= 10; i++)
  printf("%i\n", i);
int i = 1;
for (; i <= 10;)
  printf("%i\n", i++);

Of course, this is nothing but a strange-looking while loop now.

int i = 1;
while (i <= 10)
  printf("%i\n", i++);
You can even omit the second expression, but this would lead to an infinite loop, since the default empty expression is true!
int i = 1;
for (;;)
  printf("%i\n", i++);
If you want to exit from the loop prematurely, you can use the break statement:
breaking out of infinite forbreaking out of infinite while
int i = 1;
for (;;)
{
  printf("%i\n", i++);
  if (i > 10)
    break;
}
int i = 1;
while (1)
{
  printf("%i\n", i++);
  if (i > 10)
    break;
}

The break statement can be used in any of the looping mechanisms as well as the switch statement.


You can also have multiple expressions in between the semicolons separated by commas:
Using a for loopUsing a while loop
int i;
int j;
for (i = 0, j = 0; i < 16 || j < 3; i +=2, j++)
  printf("%i * %i = %i\n", i, j, i * j);
  
0 * 0 = 0
2 * 1 = 2
4 * 2 = 8
6 * 3 = 18
8 * 4 = 32
10 * 5 = 50
12 * 6 = 72
14 * 7 = 98  
int i = 0;
int j = 0;
while (i < 16 || j < 3)
{
  printf("%i * %i = %i\n", i, j, i * j);
  i += 2;
  j++;
}

Note the use of the comma operator used in the expressions. This operator has the form:

expression1 , expression2 , expression3 , etc...


The continue statement is similar to the break statement in that it causes the loop to deviate from its prescribed course. The difference is subtle, but very important.

break statementcontinue statement
for (/* expressions */)
{
  /* first statement in loop  */
  /* second statement in loop */
  /* etc...                   */

  break;

  /* last statement in loop   */
}
[break jumps to here]
/* first statement after loop */

for (/* expressions */)
{
  /* first statement in loop  */
  /* second statement in loop */
  /* etc...                   */

  continue;

  /* last statement in loop   */
  [continue jumps to here]
}
/* first statement after loop */

This prints the even numbers from 2 to 20:

using forusing whileusing while
for (i = 2; i <= 20; i++)
{
  if ( (i % 2) == 1 )
    continue;
  printf("%i\n", i);
}

2
4
6
8
10
12
14
16
18
20
i = 2;
while (i <= 20)
{
  if ( (i % 2) == 1 )
  {
    i++;
    continue;
  }
  printf("%i\n", i++);
}
i = 2;
while (i <= 20)
{
  if ( (i++ % 2) == 1 )
    continue;
  printf("%i\n", i - 1);
}

The break and continue statements are not used all that often inside of a loop, but when you need this behavior, they come in handy.

Nested Loops

Sometimes we need to have one loop inside another. This is very popular when printing a table of some sort. Just as loops are designed to be used with arrays, nested loops are desired for 2-dimensional arrays (e.g. matrices, x-y grid) or any type of data that is represented with rows and columns.

For example, printing your multiplication table for the values from 1 to 10 would look something like this:

    1    2    3    4    5    6    7    8    9   10
    2    4    6    8   10   12   14   16   18   20
    3    6    9   12   15   18   21   24   27   30
    4    8   12   16   20   24   28   32   36   40
    5   10   15   20   25   30   35   40   45   50
    6   12   18   24   30   36   42   48   54   60
    7   14   21   28   35   42   49   56   63   70
    8   16   24   32   40   48   56   64   72   80
    9   18   27   36   45   54   63   72   81   90
   10   20   30   40   50   60   70   80   90  100
And the code would look something like this:
int i, j;

for (i = 1; i <= 10; i++)
{
  for (j = 1; j <= 10; j++)
    printf("%5i", i * j);

  printf("\n");
}
You will see this a lot if you work with matrices (2-dimensional arrays) where one variable will be traversing the rows of the matrix and the other variable will be traversing the columns of the matrix. Essentially, most of the time that you are dealing with data that has rows and columns, you will be using nested loops.

Sometimes you may even need to have 3 loops nested. Suppose you want to produce a table that shows all combinations of the integers, 1, 2, and 3 as well as the sum of the integers. This would yield 27 (3 * 3 * 3) rows of 3 columns:

1,1,1, sum is 3
1,1,2, sum is 4
1,1,3, sum is 5
1,2,1, sum is 4
1,2,2, sum is 5
1,2,3, sum is 6
1,3,1, sum is 5
1,3,2, sum is 6
1,3,3, sum is 7
2,1,1, sum is 4
2,1,2, sum is 5
2,1,3, sum is 6
2,2,1, sum is 5
2,2,2, sum is 6
2,2,3, sum is 7
2,3,1, sum is 6
2,3,2, sum is 7
2,3,3, sum is 8
3,1,1, sum is 5
3,1,2, sum is 6
3,1,3, sum is 7
3,2,1, sum is 6
3,2,2, sum is 7
3,2,3, sum is 8
3,3,1, sum is 7
3,3,2, sum is 8
3,3,3, sum is 9
This is how you might code it:
int i, j, k;
int size = 3;

for (i = 1; i <= size; i++)
  for (j = 1; j <= size; j++)
    for (k = 1; k <= size; k++)
      printf("%i,%i,%i\n", i, j, k);
The break statement is often used in nested loops, when you find that, in an inner loop, you no longer need to keep looping. However, remember that the break statement only breaks out of the current (inner) loop, not all of them. If you want to break all the way out, you need to have some kind of variable (called a flag) that indicates this.

For example, given the code above, supposed we wanted to stop printing results when the sum of the three numbers (i, j, k) is 8. This is an example of how we might do that:

void break3a(void)
{
  int i, j, k;    /* Loop counters                         */
  int size = 3;   /* The max value for each loop           */
  int target = 8; /* Stop when the sum reaches this number */
  int done = 0;   /* Flag that indicates to stop looping   */

    /* Print all combinations until they add up to target */
    /* The braces are required for multiple statements    */
  for (i = 1; i <= size; i++)
  {
    for (j = 1; j <= size; j++)
    {
      for (k = 1; k <= size; k++)
      {
        int sum = i + j + k; /* We want to stop when they add up to target */

        printf("%i,%i,%i, sum is %i\n", i, j, k, sum);
        if (sum == target)
        {
          done = 1; /* Need to communicate with the outer loops */
          break;
        }
      }
        /* If the numbers add up to target, we're done, otherwise, keep going */
      if (done)
        break;
    }
      /* If the numbers add up to target, we're done, otherwise, keep going */
    if (done)
      break;
  }
}
This is the output:
1,1,1, sum is 3
1,1,2, sum is 4
1,1,3, sum is 5
1,2,1, sum is 4
1,2,2, sum is 5
1,2,3, sum is 6
1,3,1, sum is 5
1,3,2, sum is 6
1,3,3, sum is 7
2,1,1, sum is 4
2,1,2, sum is 5
2,1,3, sum is 6
2,2,1, sum is 5
2,2,2, sum is 6
2,2,3, sum is 7
2,3,1, sum is 6
2,3,2, sum is 7
2,3,3, sum is 8
This is another way to achieve the same results:
void break3b(void)
{
  int i, j, k;    /* Loop counters                         */
  int size = 3;   /* The max value for each loop           */
  int target = 8; /* Stop when the sum reaches this number */
  int done = 0;   /* Flag that indicates to stop looping   */

    /* Print all combinations until they add up to target */
  for (i = 1; i <= size && !done; i++)
  {
    for (j = 1; j <= size && !done; j++)
    {
      for (k = 1; k <= size && !done; k++)
      {
        int sum = i + j + k; /* We want to stop when they add up to target */

        printf("%i,%i,%i, sum is %i\n", i, j, k, sum);
        if (sum == target)
          done = 1; /* Need to communicate with all of the loops */
      }
    }
  }
}
There is a limit to how deeply you can nest the loops, but it's pretty big. It's bigger than what any human could comprehend. Of course, having 100 levels would be impossible for a human (programmer) to understand.