Tutorial - Loops

Main Page
Helpful Links
Downloads
Tutorials
Grades
Syllabus
Contact Me

Loops are really a natural extension of the conditionals we've covered.  Think of a loop as a block of code with a condition attached.  The block will continue to execute for as long as the condition is true.  There are three kinds of loops in C:

1.) while loops
2.) do-while loops
3.) for loops

while loops

while (condition)
   statement;

while (condition){
   // code block
}

A while loop is only entered if the condition is true.  Execution will then repeat until the condition becomes false.

do-while loops

do statement;
while (condition);

do {
   // code block; }
while (condition);

   A do-while loop is almost exactly like the while loop, except the statement or codeblock will always be executed at least once, regardless of the truth of the condition.  Repitition will then be determined by the condition.


for loops

for (initialization; condition; update)
   statement;

for (initialization; condition; update){
   // code block;
}

   The for loop is a sort of shorthand for loops indexed by a number.  They are very convenient.  Before it runs, the initialization is run, usually setting some variable to a value.  Then, the condition is tested.  If true, the loop runs.  Then, every time it finishes, the update portion is performed, and the condition is tested again.  Perhaps a real example would help:

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

When run, it prints out numbers from 0 to 9, like so:

0
1
2
3
4
5
6
7
8
9

   Pay careful attention to make sure your for-loops  execute the exact number of times you desire.  Usually, changing the condition  of the loop is appropriate.


Infinite Loops

   When a loop is written in such a way that its stopping condition will never naturally be reached (intentionally or otherwise) we call it an infinite loop.
   There are two ways to terminate an endless loop.  One is for the program to execute a break statement.  Here is an example of such a setup, used commonly in games and other interactive applications.

int main(){
   init();  // run an initialization function once
   while (1){  // here we enter an infinite loop, because 1 will always be true
      doframe();
      if (quit())
         break;  // escape with break if quit function returns true
   }
   cleanup();  // do cleanup releasing resources and stuff
}

   More commonly in our programs, infinite loops will be an unforseen mistake.  When this happens, your program might seem to freeze, or repeatedly print something out.  When this happens, the program must be killed.  The way to this under Unix is to hold the Ctrl key and type c.  This sends a kill signal to a program under Unix.
   So, when you're doing your homework and your program gets stuck in an endless loop, use Ctrl-C to escape.