While_loop While_loop

While loop - Definition and Overview

Related Words: Although, Bit, Chronology, Continuity, Day, Duration, Entertain, Hour, Interval, Kairos

In most computer programming languages, a while loop is a control structure that allows code to be executed repeatedly based on a given Boolean condition.

The while construct consists of a block of code and a condition. The condition is first evaluated - if the condition is true the code within the block is then executed. This repeats until the condition becomes false. Because while loops check the condition before the block is executed, the control structure is often also known as a pre-test loop. Compare with the do while loop, which tests the condition after the loop has executed.

Note that it is possible, and in some cases desirable, for the condition to always evaluate to true, creating an infinite loop. When such a loop is created intentionally, there is usually another control structure (such as a break statement) that controls termination of the loop.

For example, in the C programming language, the code fragment

x = 0;
while (x < 3)
{
   x++;
}

firstly checks whether x is less than 3, which it is not, so it increments x by 1. It then checks the condition again, and executes again, repeating this process until the variable x has the desired value, 3.

Demonstrating while loops

These while loops will calculate the factorial of a number:

In QBasic or Visual Basic:

 Dim Counter as Byte, Factorial as Long
 Counter = 5 'Value to take factorial of.
 Factorial = 1
 While (Counter > 0)
   Factorial = Factorial * Counter
   Counter = Counter - 1
 Wend
 Print Factorial 'Prints out the result.

In C or C++:

 int main() {
   unsigned int Counter = 5;
   unsigned long Factorial = 1;
   while (Counter > 0)
     Factorial *= Counter--; /*Multiply, then decrement.*/
   printf("%i", Factorial);
   return 0;
 }

In Tcl (Tool command language)

 set counter 5
 set factorial 1
 while {$counter > 0} {
      set factorial [expr $factorial * $counter]
          incr counter -1
  }
 puts $factorial


In Java programming language:

 int Counter = 5;
 int Factorial = 0;
 while (Counter > 0){
    Factorial *= Counter--;
 }
 System.out.println(Factorial);

Example Usage of While

givebackmycd: I get to the doctor's office super early to do the whole change of insurance thing, thinking it would take a While. Took 3 minutes. Awkward.
Norris_Ryan: How are u running online? I might sit on 2/5 RT @GazawayTM: grinding micros online for a little While, then grinding at kinser's tonight
aaronwhite: California folks: you look like hippies w/ your 3hr lag time. East-coasters been ripping it up in cold & dark While you were still in REM!
Copyright 2009 WordIQ.com - Privacy Policy  :: Terms of Use  :: Contact Us  :: About Us
This article is licensed under the GNU Free Documentation License. It uses material from the this Wikipedia article.