Search Contact information
University of Cambridge Home Department of Engineering
University of Cambridge >  Engineering Department >  computing help
next up previous contents
Next: Exercises 1 Up: Constructions Previous: Selection   Contents

Loops

...
while(i<30){    /* test at top of loop */
  something();
...
}

...
do {
   something();
} while (i<30); /* test at bottom of loop */
...

The `for' construction in C is very general. In its most common form it's much like for in other languages. The following loop starts with i set to 0 and carries on while i<5 is true, adding 1 to i each time round.

...
for(i=0; i<5; i=i+1){ 
   something();
}
...

The general form of `for' is

for ([expression1]; [expression2]; [expression3])
     something();
where all the expressions are optional. The default value for expression2 (the while condition) is 1 (true). Essentially, the for loop is a while loop. The above for loop is equivalent to
...
expression1; /* initialisation */
while (expression2){ /* condition */
   something();
   expression3;      /* code done each iteration */
};
...

E.g. the 2 fragments below are equivalent. `i' is set to 3, the loop is run once for i=3 and once for i=4, then iteration finishes when i=5.

for (i = 3; i < 5; i=i+1)
   total = total + i;
i = 3;
while(i < 5){
  total = total + i;
  i=i+1;
}

Within any of the above loop constructions, continue stops the current iteration and goes to the next and break stops the iterations altogether. E.g. in the following fragment 0 and 2 will be printed out.

...
i=0;
while (i<5){
   if (i==1){
     i = i+1;
     continue;
   }
   if (i==3)
     break;
   printf("i = %d\n", i);
   i=i+1;
}
...

If you want a loop which only ends when break is done, you can use `while(1)' (because 1 being non-zero, counts as being true) or `for(;;)'.

The { } symbols are used to compound statements. You can declare variables at the start of any compound statement. For instance, if you're worried about the scope of an index variable in a for loop, you could do the following.

{int i;
 for (i=1;i<5;i++)
    printf("i is %d\n",i);
}


next up previous contents
Next: Exercises 1 Up: Constructions Previous: Selection   Contents
Tim Love 2010-04-27