Introduction to Programming

Loops

A loop is a group of instructions that can be run more than once.

While Loop

Type yellow text exactly, and replace blue text with something else.
while (condition)
{
    instructions...
}
A while loop runs over and over and over again until the condition is false. The condition can be any expression that evaluates to true or false. For example:
1 == 2
is always false, while
5 == 5
is always true. If you use a condition that is always false, the loop will never run. Not even once. If you use a condition that is always true, the loop will run forever and never get out -- we call that an infinite loop. So in a real program we would use a condition that will be true for a while, and then after one or more times through the loop, it will become false. For example:
int a=0;
while (a < 10)
{
    a = a + 1;
}
This loop would execute 10 times. After that, a would no longer be less than 10, so the loop exits and the program goes on to the next instruction after the loop.

For loop

for loops are slightly more complicated. Instead of just one thing in between the parentheses, there are three things! Take a look:
for (initialization; condition; action)
{
    instructions...
}
This kind of loop is almost like a while loop, in that it has a condition, and the loop keeps going over and over until the condition is false. The difference is that it has an "initialization" and "action" part in that first line. The initialization part happens exactly once at the very beginning of the loop. The action part happens each time the loop gets to the end of the loop. The condition part is checked after the initialization part, and then after each action part. For example:
int a;
for (a=0; a<10; a++)
{
    printf("a is %d\n", a);
}
During initialization, the loop sets a to 0. Then the condition is checked. Yes, 0 is less than 10, so the loop starts. So the body of the loop runs, and 0 is printed on the screen. Then the action happens. The action says "a++", which means increment a. So a becomes 1. Now the condition is checked again, and yes, 1 is still less than 10, so the loop runs again, and 1 is put on the screen. This keeps going on again and again until the action sets a to 10. Then the condition "10 < 10" fails (it evaluates to false), so the loop exits. In the end what you get on the screen is the numbers 0 through 9. If that doesn't make sense, try running through the example in your head. Remember the steps:
  1. Do the initialization (a=0)
  2. Check the condition (a<10)
  3. If the condition passes, go on to step 4. If it fails, you're done with the loop.
  4. Run the instructions inside the curly brackets {}.
  5. Do the action (a++) (that means increase a by 1).
  6. Go back to step 2.


Next: Arrays

Previous: printf


Introduction to Programming

Home