1. Home
  2. Computing & Technology
  3. C / C++ / C#

C Tutorial - Lesson Five - About Control Statements

By , About.com Guide

4 of 5

While and Do While

There are two loop statements that use while.

First is the while statement which has this syntax.

while (expression) statement
As long as the expression is true, the statement is executed.
int total =0;
int index =0;
while (total < 100)
{
index++;
total+=index;
printf("Sum of 1 to %i is %i",index,total) ;
}

Looping doesn't get much simpler than while. The most important thing to know with while loops is that the control expression is evaluated before the statement is run. If the expression is false, the statement is not run. So a while loop may never execute a statement.

Also because c allows a statement to be an expression it is possible to write complicated code like this

int c=10;
int a =0;
while (c--)
{
printf("Value of a is %i",a++) ;
}
c-- subtracts one from c.

Do While

Less popular than the while statement is the do while statement. This puts the expression at the end.

The syntax looks like this.

do
statement;
while (expression) ;
A while loop might never execute a statement if the expression is false but a do while will always execute the statement at least once.

Here is an example of a do while loop.

int count =0;
int index =9;
do
if (value[ index] ==999)
count++;
index--;
while ( index >= 0) ;
Break and Continue work equally well with for, while and do while loops.

On the next page : learn about Switch statements.

Explore C / C++ / C#
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C
  5. C Tutorials
  6. While and Do While

©2009 About.com, a part of The New York Times Company.

All rights reserved.