While loop
Encyclopedia
In most computer programming
Computer programming
Computer programming is the process of designing, writing, testing, debugging, and maintaining the source code of computer programs. This source code is written in one or more programming languages. The purpose of programming is to create a program that performs specific operations or exhibits a...

 languages, a while loop is a control flow
Control flow
In computer science, control flow refers to the order in which the individual statements, instructions, or function calls of an imperative or a declarative program are executed or evaluated....

 statement
Statement (programming)
In computer programming a statement can be thought of as the smallest standalone element of an imperative programming language. A program written in such a language is formed by a sequence of one or more statements. A statement will have internal components .Many languages In computer programming...

 that allows code to be executed repeatedly based on a given boolean
Boolean datatype
In computer science, the Boolean or logical data type is a data type, having two values , intended to represent the truth values of logic and Boolean algebra...

 condition. The while loop can be thought of as a repeating if statement
Conditional statement
In computer science, conditional statements, conditional expressions and conditional constructs are features of a programming language which perform different computations or actions depending on whether a programmer-specified boolean condition evaluates to true or false...

.

The while construct consists of a block of code and a condition. The condition is evaluated, and if the condition is true
Logical value
In logic and mathematics, a truth value, sometimes called a logical value, is a value indicating the relation of a proposition to truth.In classical logic, with its intended semantics, the truth values are true and false; that is, classical logic is a two-valued logic...

, the code within the block is executed. This repeats until the condition becomes false
False
False or falsehood may refer to:*False *Lie or falsehood, a type of deception in the form of an untruthful statement*Falsity or falsehood, in law, deceitfulness by one party that results in damage to another...

. 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
Do while loop
In most computer programming languages, a do while loop, sometimes just called a do loop, is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. Note though that unlike most languages, Fortran's do loop is actually analogous to the for loop.The...

, which tests the condition after the loop has executed.

For example, in the C programming language
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....

 (as well as Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

 and C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...

, which use the same syntax in this case), the code fragment


x = 0;
while (x < 5)
{
printf ("x = %d\n", x);
x++;
}


first checks whether x is less than 5, which it is, so then the {loop body} is entered, where the printf function is run and x is incremented by 1. After completing all the statements in the loop body, the condition, (x < 5), is checked again, and the loop is executed again, this process repeating until the variable
Variable (programming)
In computer programming, a variable is a symbolic name given to some known or unknown quantity or information, for the purpose of allowing the name to be used independently of the information it represents...

 x has the value 5.

Note that it is possible, and in some cases desirable, for the condition to always evaluate to true, creating an infinite loop
Infinite loop
An infinite loop is a sequence of instructions in a computer program which loops endlessly, either due to the loop having no terminating condition, having one that can never be met, or one that causes the loop to start over...

. When such a loop is created intentionally, there is usually another control structure (such as a break
Control flow
In computer science, control flow refers to the order in which the individual statements, instructions, or function calls of an imperative or a declarative program are executed or evaluated....

 statement) that controls termination of the loop.
For Ex.


while (1)
{
if(SomeCondition)
break;
}


Equivalent constructs


while (condition) {
statements;
}


is equivalent to


if (condition) {
do {
statements;
} while (condition);
}


or


while (true) {
if (!condition) break;
statements;
}

or


goto TEST;
LOOPSTART:
statements;
TEST:
if (condition) goto LOOPSTART;


or


TEST:
if (!condition) goto LOOPEND;
statements
goto TEST;
LOOPEND:


Also, in C
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....

 and its descendants, a while loop is a for loop with no initialization or counting expressions, i.e.,


for ( ; condition; )
{
statements;
}

ActionScript 3


var i:int = 1;

while ( i < 6)
{
trace ("Number ", i);
i = i*i;
}

Ada
Ada (programming language)
Ada is a structured, statically typed, imperative, wide-spectrum, and object-oriented high-level computer programming language, extended from Pascal and other languages...


with Ada.Integer_Text_IO;

procedure Factorial is
Counter : Integer := 5;
Factorial : Integer := 1;
begin
while Counter > 0 loop
Factorial := Factorial * Counter;
Counter := Counter - 1;
end loop;

Ada.Integer_Text_IO.Put (Factorial);
end Factorial;

Bash


counter=5
factorial=1
while [ $counter -gt 0 ]; do
factorial=$((factorial * counter))
counter=$((counter - 1))
done

echo $factorial

QBasic
QBasic
QBasic is an IDE and interpreter for a variant of the BASIC programming language which is based on QuickBASIC. Code entered into the IDE is compiled to an intermediate form, and this intermediate form is immediately interpreted on demand within the IDE. It can run under nearly all versions of DOS...

 or Visual Basic
Visual Basic
Visual Basic is the third-generation event-driven programming language and integrated development environment from Microsoft for its COM programming model...



Dim counter As Integer = 10 ' init variable and set value

Do While counter > 0
counter = counter - 1
Loop ' program goes here, until counter = 0


C
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....

 or C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...


unsigned int counter = 5;
unsigned long factorial = 1;

while (counter > 0)
{
factorial *= counter--; /* Multiply and decrement */
}

printf("%lu", factorial);

Fortran
Fortran
Fortran is a general-purpose, procedural, imperative programming language that is especially suited to numeric computation and scientific computing...


program FactorialProg
integer :: counter = 5
integer :: factorial = 1
do while (counter > 0)
factorial = factorial * counter
counter = counter - 1
end do
print *, factorial
end program FactorialProg

Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

, C#, D
D (programming language)
The D programming language is an object-oriented, imperative, multi-paradigm, system programming language created by Walter Bright of Digital Mars. It originated as a re-engineering of C++, but even though it is mainly influenced by that language, it is not a variant of C++...

The code for the loop is the same for Java, C# and D:


int counter = 5;
long factorial = 1;

while (counter > 1)
{
factorial *= counter--;
}


For Java the result is printed as follows:
System.out.println(factorial);

The same in C#
System.Console.WriteLine(factorial);

And finally in D
writefln(factorial);

JavaScript
JavaScript
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....


var counter = 5;
var factorial = 1;

while ( counter > 1 )
{
factorial *= counter--;
}

document.write(factorial);

Lua


counter = 5
factorial = 1

while counter > 0 do
factorial = factorial * counter
counter = counter - 1
end

print(factorial)

MATLAB
MATLAB
MATLAB is a numerical computing environment and fourth-generation programming language. Developed by MathWorks, MATLAB allows matrix manipulations, plotting of functions and data, implementation of algorithms, creation of user interfaces, and interfacing with programs written in other languages,...


counter = 5;
factorial = 1;

while (counter > 0)
factorial = factorial * counter; %Multiply
counter = counter - 1; %Decrement
end

factorial

Mathematica
Mathematica
Mathematica is a computational software program used in scientific, engineering, and mathematical fields and other areas of technical computing...

Block[{counter=5,factorial=1}, (*localize counter and factorial*)
While[counter>0, (*While loop*)
factorial*=counter; (*Multiply*)
counter--; (*Decrement*)
];
factorial
]

Oberon
Oberon (programming language)
Oberon is a programming language created in 1986 by Professor Niklaus Wirth and his associates at ETH Zurich in Switzerland. It was developed as part of the implementation of the Oberon operating system...

, Oberon-2
Oberon-2
Oberon-2 is an extension of the original Oberon programming language that adds limited reflection and object-oriented programming facilities, open arrays as pointer base types, read-only field export and reintroduces the FOR loop from Modula-2....

, Oberon-07, or Component Pascal
Component Pascal
Component Pascal is a programming language in the tradition of Niklaus Wirth's Pascal, Modula-2, Oberon and Oberon-2. It bears the name of the Pascal programming language but is incompatible with it. Instead, it is a minor variant and refinement of Oberon-2, designed and supported by a small ETH...


MODULE Factorial;
IMPORT Out;
VAR
Counter, Factorial: INTEGER;
BEGIN
Counter := 5;
Factorial := 1;
WHILE Counter > 0 DO
Factorial := Factorial * Counter;
DEC(Counter)
END.
Out.Int(Factorial,0)
END Factorial.

Pascal


program Factorial1;
var
Counter, Factorial: integer;
begin
Counter := 5;
Factorial := 1;
while Counter > 0 do
begin
Factorial := Factorial * Counter;
Counter := Counter - 1
end;
WriteLn(Factorial)
end.

Perl
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...


my $counter = 5;
my $factorial = 1;

while ( $counter > 0 ) {
$factorial *= $counter--; # Multiply, then decrement
}

print $factorial;


Very similar to C and C++, but the while loop could also have been written on one line:

$factorial *= $counter-- while $counter > 0;

While loops are frequently used for reading data line by line (as defined by the $/ line separator) from open filehandles:


open IN, " while ( ) {
print;
}
close IN;

PHP
PHP
PHP is a general-purpose server-side scripting language originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document...


$counter = 5;
$factorial = 1;
while($counter > 0) {
$factorial *= $counter; // Multiply first.
$counter--; // then decrement.
}
print $factorial;

Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...


counter = 5 # Set the value to 5
factorial = 1 # Set the value to 1

while counter > 0: # While counter(5) is greater than 0
factorial = factorial * counter # Set new value of factorial to
# factorial x counter.

counter = counter - 1 # Set the new value of counter to
# counter - 1.

print factorial # Print the value of factorial.


Non Terminating While Loop:-


while 1 1:
print "Help! I am Lost in this Loop."

Racket

In Racket, as in other Scheme implementations, a "named-let" is a popular way to implement loops:
  1. lang racket

(define counter 5)
(define factorial 1)
(let loop
(when (> counter 0)
(set! factorial (* factorial counter))
(set! counter (sub1 counter))
(loop)))
(displayln factorial)

Using a macro system, implementing a while-loop is a trivial exercise (commonly used to introduce macros):
  1. lang racket

(define-syntax-rule (while test body ...) ; implements a while loop
(let loop (when test body ...) (loop)))
(define counter 5)
(define factorial 1)
(while (> counter 0)
(set! factorial (* factorial counter))
(set! counter (sub1 counter)))
(displayln factorial)

But note that an imperative programming style is often discouraged in Racket (as in Scheme).

Smalltalk
Smalltalk
Smalltalk is an object-oriented, dynamically typed, reflective programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." It was designed and created in part for educational use, more so for constructionist...

Contrary to other languages, in Smalltalk a while loop is not a language construct
Language construct
A language construct is a syntactically allowable part of a program that may be formed from one or more lexical tokens in accordance with the rules of a programming language....

 but defined in the class BlockClosure as a method with one parameter, the body as a closure
Closure
Closure may refer to:* Closure used to seal a bottle, jug, jar, can, or other container** Closure , a stopper* Closure , the process by which an organization ceases operations...

, using self as the condition.

Smalltalk also has a corresponding whileFalse: method.


| count factorial |
count := 5.
factorial := 1.
[ count > 0 ] whileTrue:
[ factorial := factorial * count
count := count - 1 ]
Transcript show: factorial

Tcl
Tcl
Tcl is a scripting language created by John Ousterhout. Originally "born out of frustration", according to the author, with programmers devising their own languages intended to be embedded into applications, Tcl gained acceptance on its own...

 (Tool command language)


set counter 5
set factorial 1

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

puts $factorial

Windows PowerShell
Windows PowerShell
Windows PowerShell is Microsoft's task automation framework, consisting of a command-line shell and associated scripting language built on top of, and integrated with the .NET Framework...

$counter = 5
$factorial = 1
while ($counter -gt 0) {
$factorial *= $counter-- # Multiply, then decrement.
}
Write-Output $factorial
The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK