While loop
Encyclopedia
In most computer programming
languages, a while loop is a control flow
statement
that allows code to be executed repeatedly based on a given boolean
condition. The while loop can be thought of as a repeating if statement
.
The while construct consists of a block of code and a condition. The condition is evaluated, and if the condition is true
, the code within the block is 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.
For example, in the C programming language
(as well as Java
and C++
, which use the same syntax in this case), the code fragment
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
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
. 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 Ex.
is equivalent to
or
or
or
Also, in C
and its descendants, a while loop is a for loop with no initialization or counting expressions, i.e.,
Ada
QBasic
C
Fortran
Java
The code for the loop is the same for Java, C# and D:
For Java the result is printed as follows:
The same in C#
And finally in D
JavaScript
MATLAB
Mathematica
Block[{counter=5,factorial=1}, (*localize counter and factorial*)
While[counter>0, (*While loop*)
factorial*=counter; (*Multiply*)
counter--; (*Decrement*)
];
factorial
]
Oberon
Perl
Very similar to C and C++, but the while loop could also have been written on one line:
While loops are frequently used for reading data line by line (as defined by the
PHP
Python
Non Terminating While Loop:-
Using a macro system, implementing a while-loop is a trivial exercise (commonly used to introduce macros):
But note that an imperative programming style is often discouraged in Racket (as in Scheme).
Smalltalk
Contrary to other languages, in Smalltalk a while loop is not a language construct
but defined in the class
, using self as the condition.
Smalltalk also has a corresponding whileFalse: method.
Tcl
Windows PowerShell
$counter = 5
$factorial = 1
while ($counter -gt 0) {
$factorial *= $counter-- # Multiply, then decrement.
}
Write-Output $factorial
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
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.
Equivalent constructs
is equivalent to
or
or
or
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.,
ActionScript 3
AdaAda (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...
Bash
QBasicQBasicQBasic 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 BasicVisual BasicVisual Basic is the third-generation event-driven programming language and integrated development environment from Microsoft for its COM programming model...
CC (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...
FortranFortranFortran is a general-purpose, procedural, imperative programming language that is especially suited to numeric computation and scientific computing...
JavaJava (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#, DD (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:For Java the result is printed as follows:
The same in C#
And finally in D
JavaScriptJavaScriptJavaScript 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....
Lua
MATLABMATLABMATLAB 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,...
MathematicaMathematicaMathematica 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
]
OberonOberon (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-2Oberon-2Oberon-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 PascalComponent PascalComponent 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...
Pascal
PerlPerlPerl 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...
Very similar to C and C++, but the while loop could also have been written on one line:
While loops are frequently used for reading data line by line (as defined by the
$/
line separator) from open filehandles:PHPPHPPHP 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...
PythonPython (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...
Non Terminating While Loop:-
Racket
In Racket, as in other Scheme implementations, a "named-let" is a popular way to implement loops:Using a macro system, implementing a while-loop is a trivial exercise (commonly used to introduce macros):
But note that an imperative programming style is often discouraged in Racket (as in Scheme).
SmalltalkSmalltalkSmalltalk 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 constructLanguage 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 closureClosure
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.
TclTclTcl 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)
Windows PowerShellWindows PowerShellWindows 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