Vinay's C Tutorial

Loops

What are loops?

In all programs you're written so far, execution begins at the start of the main() function and proceeds line by line till the end of the program. But what if you want to do something repeatedly? Say, print something on the screen ten times? Or print the numbers 1 to 10? Sure, you could include 10 printf statements. But what if you wanted to do it a hundred times, or a thousand. Obviously, duplicating code is not the answer. To do repetative tasks, we use loops. In C there are several types of loops, which can be used for different purposes. In this chapter we'll deal with the while, do and for loops. You'll also learn how to write simple expressions. Expressions will then be dealt with in more detail in the next chapter.

The while Loop

A loop is a portion of code that executes repeatedly, till some condition is satisfied. A loop allows a relatively short program to do quite a bit. There are several type of loops available in C, each with its own uses. The most basic of these is the while loop. The following program uses a while loop to print the numbers 1 to 20 on the screen.

/* while.c   Demonstrates while loops
     ^ note that I've named the program while.c. You can call it anything but I've given it a name so that it'll be easier to refer to it in the future.
*/

#include <stdio.h>

main()
{
     int x = 1;
     while (x <= 20)
     {
          x = x + 1;
          printf ("%d\n", x);
     }
}

If you run the program, you'll see that it prints the numbers from 1 to 20, one on each line.

If the program seems a little complicated, just read it again. It'll make sense. Like all programs we've written so far, it begins by #include-ing the stdio.h file, and then declaring the main function. The main function itself starts off pretty simple. It declares the variable x and assigns a value of one to it. Does the next line seem rather confusing? Try reading it out - while x (is) less than (or) equal to twenty. That makes the meaning rather obvious doesn't it? The two statements enclosed in braces will be executed repeatedly until x becomes greater than twenty.

Mathematically speaking, x = x + 1 seems rather silly. But in C, = is an assignment operator (more on operators in a moment). So it tells to computer to calculate x + 1 and assign the value to x itself.

While is defined as follows -

while (expression)
     statement;

The statement will be executed repeatedly so long as the expression remains true. When the while is reached, the computer evaluates expression. If it is found to be false, statement will not be executed, and the loop ends. Otherwise statement is executed, then expression is checked again and so on, till expression becomes false.

Note that there is no semicolon (;) after while (expression).

Compound Statements

In C, wherever you can use one statement, you can also use several statements enclosed in braces {}. Such a collection of statements is called a compound statement. Based on the definition of while a while loop should look like this-

while (x < 10000)
     x = x + 1;

However, you saw that in while.c, we used not one statement, but two statements enclosed in braces, i.e. a compound statement.

Variables can be declared the begining of any compound statement, not just function definitions. Such variables will exist only in that particluar compound statement, and are called automatic variables. For example,

while (x < 20)     /* x is some variable declared outside the while loop */
{
     int y;

     y = x * 15;
     x = x + 1;
     printf ("%d", y);
}

Note that you can't assume that an automatic variable will retain the same value between two executions of the statement (unless they're static, as we shall see in a later chapter). For example, the following code will not correctly calculate the sum:

while (x < 20)
{
     int Sum = 0;

     x = x + 1;
     Sum = Sum + x;
}

To calculate the sum, the Sum variable should be declare outside the while compound statement.

Expressions

Expressions are important for loops to work. For example, the while loop will execute so long as the expression remains true. Expressions will be dealt with in detail in a later chapter, but you should know how to build simple expressions, right now. Basically, an expression consists of one or more values or variables, connected be zero or more operators. The numbers of values or variables required depends on the operator used. Following is a list of operators you'll need at the moment

Operator Name Example Meaning Boolean?
= Assignment x = y Assign value of y to x No
+ Addition x + y x plus y No
- Subtraction x - y x minus y No
* Multiplication x * y x multiplied by y No
/ Division x / y x divided by y No
== Equal to x == y Is x equal to y? Yes
< Less than x < y Is x less than y? Yes
> Greater than x > y Is x greater than y? Yes
<= Less than or equal to x <= y Is x less than or equal to y? Yes
>= Greater than or equal to x >= y Is x greater than or equal to y? Yes
!= Not equal to x != y Is x not equal to y? Yes
! Unary 'not' !x Is x zero? Yes

Boolean operators are ones that result in one of only two possible values - True or False. A zero is considered false, and a one, true. So, the value of x == y is zero if x is not equal to y, and one if x is equal to y.

In C there is no real boolean data type. In C zero is considered false, and any non-zero value, be it 1, -1 or 25000, is considered true.

One common use of this fact is to create an infinite loop using while, like this: while (1)
...;
This executes the statement again and again, infinitely. Infinite loops may not seem particularly useful... after all, you don't want your user to wait forever, watching your program execute, do you? As you'll see in the chapter on Control Flow, there are ways of exiting infinite loops gracefully.

As mentioned earlier, the while statement will repeatedly execute so long as the expression is true. This means that the statement will repeatedly execute while the value of the expression is non-zero. Boolean operators will return zero or one depending on the truth of the expression, but any expression can be used. For example,

int x = 5, y = 0;

while (x - y)
{
     y = y + 1;
     printf ("%d\n", y);
}

In the above code fragment, the expression x - y is evaluated. The value of x - y will become zero only when y become 5, so the statement will be executed till y becomes 5.

Note that in C, = and == (two = signs without a space in between) operators are different. The == is the comparision operator, used to compare two values. The = operator is used to assign the value of one variable to another, for example

x = y; /* Makes x equal to y */
x == y  /* compares x and y */

But is it an error ("illegal") to use an expression like this

int x = 5, y;

while (y = x - 1)
{

     printf ("%d\n"', y);
     x = x - 1;
}

No! What happens is, that the compiler evaluates the expression to the right of the = sign, assigns the value to the variable on the left of the = sign, and then assumes the whole expression to have that value. So, the above while statement will execute so long a x - 1 is nonzero, i.e. so long as x is not equal to 1. Moreover the value of x - 1 is assigned to y each time, so above loop prints the numbers 4, 3 and 2 and then ends.

It is not illegal to use the assignment operator = with statements like while which expect boolean operators, as described in the previous paragraph. However, is is quite a common programming error to use = instead of ==. Hence many compilers may produce a warning. If you are sure you intend to use the assignment operator, not the comparision operator, you can simply ignore the warning.

For now, we'll use only very simple expressions, since our focus is on loops. Expressions will be dealt with in greater detail in a later chapter.

Increment/Decrement Operators

In programming, one often needs to increment or decrement variables, using expressions like

x = x + 1;
y = y - 1;

This is such a common situation, that there is a shorthand notation for increment and decrement

x++   /* increment AFTER current statement - Postincrement */
++x   /* increment BEFORE current statement - Preincrement */
y--   /* decrement AFTER current statement - Postdecrement */
--y   /* decrement BEFORE current statement - Predecrement */

When used alone, both ++x and x++ do the same thing as x = x + 1. But when used as a part of another expression, they are different. With the the postincrement and postdecrement operators, the current value of the variable is used in the expression, and then the variable is incremented or decremented. With the preincrement and predecrement operators, the variable is incremented or decremented, and then the new value is used in the expression. For example,

int x = 0;

while (x < 5)
     printf ("%d\n", ++x);

This program prints the numbers 1, 2, 3, 4 and 5, but the program

int x = 0;

while (x < 5)
     printf (%d\n"", x++);

prints the numbers 0, 1, 2, 3 and 4.

The do Loop

Following is the structure of the do loop:

do
     statement;
while (expression)

In other words, the do loop first executes the statement, then exaluates the expression and executes the statement again if the expression is nonzero, and so on. For example

int x = 0;

do
{
     x++;
     printf ("&d", x);
} while (x < 5);

this statement prints the values 0, 1, 2, 3, 4, 5.

The do loop differs from the while loop only in that it executes the statement before evaluating the expression. An important consequence of this, which you should keep in mind, is that unlike a while loop, the contents of a do loop will be executed at least one. Because the while loop (and as you will see in the next section, the for loop) evaluates the expresion before executing the statement, if the condition is false (zero) right at the beginning, the statement will never be executed.

The for Loop

In all programs written so far, you must have noticed that a loop does the following three things:

  1. Initialize variables
  2. Evaluate some expression
  3. Modify variables

for example

int x = 0; /* initialize x to the value of zero */

while (x < 5) /* evaluate expression to determine whether to continue executing the loop */
{
     printf ("%d\n", x);
     x++;    /* increment x. Without this the loop would never end */ 
}

The for loop takes care of all three steps in one go. A for loop is defined as

for (init.expression; bool.expression; loop.expression)
     statement;

This is what the for loop does:

  1. Execute init.expression to do necessaty initializations
  2. Evaluate bool.expression. If true, execute statement otherwise exit the loop
  3. Execute loop.statement and then go to step 2

for example

int x;

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

this program prints the numbers 0 to 9.

In some cases, you may not want to include one or more expressions in the for statement for example

int x;

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

However, you should still include the semicolons.

You can also omit all three expressions, like this

for (;;)
     printf ("Hello, world.\n");

This simply prints the words 'Hello, world.' repeatedy, till you end the program by pressing ^C or Ctrl-Break on the keyboard. This is called an infinite loop. Generally, you would want to avoid infinite loops.

What You've Learnt

In this chapter you've learnt:

Moving Ahead

Loops form the basis of most non-trivial programs... Before moving on to the next chapter you should make sure you thouroughly understand and know how to use each type of loop. Write several programs and experiment with them. This chapter also introduced basic expressios. Make sure you can write expressions to perform calculations, and decision making that is used in loops. You shoud try the following:

The Next Step

If you've tried writing the above programs, and have understood everything done in this chapter, you're now ready to move on the next chapter.

Chapter 4: Expressions

Back to Top


I Want Your Feedback - Sign My Guestbook (View Guestbook)
If you have any suggestions, contributions or comments, E-mail me at vinaypai@crosswinds.net