While loop

Last updated
While loop flow diagram While-loop-diagram.svg
While loop flow diagram

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.

Contents

Overview

The while construct consists of a block of code and a condition/expression. [1] The condition/expression is evaluated, and if the condition/expression is true, [1] the code within all of their following in the block is executed. This repeats until the condition/expression becomes false. Because the while loop checks the condition/expression before the block is executed, the control structure is often also known as a pre-test loop. Compare this with the do while loop, which tests the condition/expression after the loop has executed.

For example, in the languages C, Java, C#, [2] Objective-C, and C++, (which use the same syntax in this case), the code fragment

intx=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 x has the value 5.

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:

while(true){// do complicated stuffif(someCondition)break;// more stuff}

Demonstrating while loops

These while loops will calculate the factorial of the number 5:

ActionScript 3

varcounter:int=5;varfactorial:int=1;while(counter>1){factorial*=counter;counter--;}Printf("Factorial = %d",factorial);

Ada

withAda.Integer_Text_IO;procedureFactorialisCounter:Integer:=5;Factorial:Integer:=1;beginwhileCounter>0loopFactorial:=Factorial*Counter;Counter:=Counter-1;endloop;Ada.Integer_Text_IO.Put(Factorial);endFactorial;

APL

counter5factorial1:Whilecounter>0factorial×countercounter-1:EndWhilefactorial

or simply

!5

AutoHotkey

counter:=5factorial:=1Whilecounter>0factorial*=counter--MsgBox%factorial

Small Basic

counter=5' Counter = 5factorial=1' initial value of variable "factorial"Whilecounter>0factorial=factorial*countercounter=counter-1TextWindow.WriteLine(counter)EndWhile

Visual Basic

DimcounterAsInteger=5' init variable and set valueDimfactorialAsInteger=1' initialize factorial variableDoWhilecounter>0factorial=factorial*countercounter=counter-1Loop' program goes here, until counter = 0'Debug.Print factorial         ' Console.WriteLine(factorial) in Visual Basic .NET

Bourne (Unix) shell

counter=5factorial=1while[$counter-gt0];dofactorial=$((factorial*counter))counter=$((counter-1))doneecho$factorial

C, C++

intmain(){intcount=5;intfactorial=1;while(count>1)factorial*=count--;printf("%d",factorial);}

ColdFusion Markup Language (CFML)

Script syntax

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

Tag syntax

<cfsetcounter=5><cfsetfactorial=1><cfloopcondition="counter GT 1"><cfsetfactorial*=counter--></cfloop><cfoutput>#factorial#</cfoutput>

Fortran

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

Go

Go has no while statement, but it has the function of a for statement when omitting some elements of the for statement.

counter,factorial:=5,1forcounter>1{counter,factorial=counter-1,factorial*counter}

Java, C#, D

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

intcounter=5;intfactorial=1;while(counter>1)factorial*=counter--;

JavaScript

letcounter=5;letfactorial=1;while(counter>1)factorial*=counter--;console.log(factorial);

Lua

counter=5factorial=1whilecounter>0dofactorial=factorial*countercounter=counter-1endprint(factorial)

MATLAB, Octave

counter=5;factorial=1;while(counter>0)factorial=factorial*counter;%Multiplycounter=counter-1;%Decrementendfactorial

Mathematica

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

Oberon, Oberon-2, Oberon-07, Component Pascal

MODULEFactorial;IMPORTOut;VARCounter,Factorial:INTEGER;BEGINCounter:=5;Factorial:=1;WHILECounter>0DOFactorial:=Factorial*Counter;DEC(Counter)END;Out.Int(Factorial,0)ENDFactorial.

Maya Embedded Language

int$counter=5;int$factorial=1;int$multiplication;while($counter>0){$multiplication=$factorial*$counter;$counter-=1;print("Counter is: "+$counter+", multiplication is: "+$multiplication+"\n");}

Nim

varcounter=5# Set counter value to 5factorial=1# Set factorial value to 1whilecounter>0:# While counter is greater than 0factorial*=counter# Set new value of factorial to counter.deccounter# Set the counter to counter - 1.echofactorial

Non-terminating while loop:

whiletrue:echo"Help! I'm stuck in a loop!"

Pascal

Pascal has two forms of the while loop, while and repeat. While repeats one statement (unless enclosed in a begin-end block) as long as the condition is true. The repeat statement repetitively executes a block of one or more statements through an until statement and continues repeating unless the condition is false. The main difference between the two is the while loop may execute zero times if the condition is initially false, the repeat-until loop always executes at least once.

programFactorial1;varFv:integer;procedurefact(counter:integer);varFactorial:integer;beginFactorial:=1;whileCounter>0dobeginFactorial:=Factorial*Counter;Counter:=Counter-1end;WriteLn(Factorial)end;beginWrite('Enter a number to return its factorial: ');readln(fv);repeatfact(fv);Write('Enter another number to return its factorial (or 0 to quit): ');untilfv=0;end.

Perl

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

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

openIN,"<test.txt";while(<IN>){print;}closeIN;

PHP

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

PL/I

declarecounterfixedinitial(5); declarefactorialfixedinitial(1);dowhile(counter>0)factorial=factorial*counter;counter=counter-1;end;

Python

counter=5# Set the value to 5factorial=1# Set the value to 1whilecounter>0:# While counter(5) is greater than 0factorial*=counter# Set new value of factorial to counter.counter-=1# Set the counter to counter - 1.print(factorial)# Print the value of factorial.

Non-terminating while loop:

whileTrue:print("Help! I'm stuck in a loop!")

Racket

In Racket, as in other Scheme implementations, a named-let is a popular way to implement loops:

#lang racket(definecounter5)(definefactorial1)(letloop()(when(>counter0)(set!factorial(*factorialcounter))(set!counter(sub1counter))(loop)))(displaylnfactorial)

Using a macro system, implementing a while loop is a trivial exercise (commonly used to introduce macros):

#lang racket(define-syntax-rule(whiletestbody...); implements a while loop(letloop()(whentestbody...(loop))))(definecounter5)(definefactorial1)(while(>counter0)(set!factorial(*factorialcounter))(set!counter(sub1counter)))(displaylnfactorial)

However, an imperative programming style is often discouraged in Scheme and Racket.

Ruby

# Calculate the factorial of 5i=1factorial=1whilei<=5factorial*=ii+=1endputsfactorial

Rust

fnmain(){letmutcounter=5;letmutfactorial=1;whilecounter>1{factorial*=counter;counter-=1;}println!("{}",factorial);}

Smalltalk

Contrary to other languages, in Smalltalk a while loop is not a language construct but defined in the class BlockClosure as a method with one parameter, the body as a closure, 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].Transcriptshow:factorial

Swift

varcounter=5// Set the initial counter value to 5varfactorial=1// Set the initial factorial value to 1whilecounter>0{// While counter(5) is greater than 0factorial*=counter// Set new value of factorial to factorial x counter.counter-=1// Set the new value of counter to  counter - 1.}print(factorial)// Print the value of factorial.

Tcl

setcounter5setfactorial1while{$counter>0}{setfactorial[expr$factorial*$counter]incrcounter-1}puts$factorial

VEX

intcounter=5;intfactorial=1;while(counter>1)factorial*=counter--;printf("%d",factorial);

PowerShell

$counter=5$factorial=1while($counter){$factorial*=$counter--}$factorial

While (language)

While [3] is a simple programming language constructed from assignments, sequential composition, conditionals, and while statements, used in the theoretical analysis of imperative programming language semantics. [4] [5]

C:=5;F:=1;while(C>1)doF:=F*C;C:=C-1;

See also

Related Research Articles

In computer programming, an infinite loop is a sequence of instructions that, as written, will continue endlessly, unless an external intervention occurs, such as turning off power via a switch or pulling a plug. It may be intentional.

In computer science, control flow is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The emphasis on explicit control flow distinguishes an imperative programming language from a declarative programming language.

<span class="mw-page-title-main">Lua (programming language)</span> Lightweight programming language

Lua is a lightweight, high-level, multi-paradigm programming language designed primarily for embedded use in applications. Lua is cross-platform, since the interpreter of compiled bytecode is written in ANSI C, and Lua has a relatively simple C API to embed it into applications.

In programming languages, a closure, also lexical closure or function closure, is a technique for implementing lexically scoped name binding in a language with first-class functions. Operationally, a closure is a record storing a function together with an environment. The environment is a mapping associating each free variable of the function with the value or reference to which the name was bound when the closure was created. Unlike a plain function, a closure allows the function to access those captured variables through the closure's copies of their values or references, even when the function is invoked outside their scope.

<span class="mw-page-title-main">C syntax</span> Set of rules defining correctly structured programs

The syntax of the C programming language is the set of rules governing writing of software in C. It is designed to allow for programs that are extremely terse, have a close relationship with the resulting object code, and yet provide relatively high-level data abstraction. C was the first widely successful high-level language for portable operating-system development.

<span class="mw-page-title-main">For loop</span> Control flow statement for repeated execution

In computer science a for-loop or for loop is a control flow statement for specifying iteration. Specifically, a for loop functions by running a section of code repeatedly until a certain condition has been satisfied.

In computer science, a generator is a routine that can be used to control the iteration behaviour of a loop. All generators are also iterators. A generator is very similar to a function that returns an array, in that a generator has parameters, can be called, and generates a sequence of values. However, instead of building an array containing all the values and returning them all at once, a generator yields the values one at a time, which requires less memory and allows the caller to get started processing the first few values immediately. In short, a generator looks like a function but behaves like an iterator.

<span class="mw-page-title-main">Foreach loop</span> Control flow statement for traversing items in a collection

In computer programming, foreach loop is a control flow statement for traversing items in a collection. foreach is usually used in place of a standard for loop statement. Unlike other for loop constructs, however, foreach loops usually maintain no explicit counter: they essentially say "do this to everything in this set", rather than "do this x times". This avoids potential off-by-one errors and makes code simpler to read. In object-oriented languages, an iterator, even if implicit, is often used as the means of traversal.

In computer programming, conditional loops or repetitive control structures are a way for computer programs to repeat one or more various steps depending on conditions set either by the programmer initially or real-time by the actual program.

In most computer programming languages, a do while loop is a control flow statement that executes a block of code and then either repeats the block or exits the loop depending on a given boolean condition.

Loop unrolling, also known as loop unwinding, is a loop transformation technique that attempts to optimize a program's execution speed at the expense of its binary size, which is an approach known as space–time tradeoff. The transformation can be undertaken manually by the programmer or by an optimizing compiler. On modern processors, loop unrolling is often counterproductive, as the increased code size can cause more cache misses; cf. Duff's device.

The computer programming languages C and Pascal have similar times of origin, influences, and purposes. Both were used to design their own compilers early in their lifetimes. The original Pascal definition appeared in 1969 and a first compiler in 1970. The first version of C appeared in 1972.

Structured text, abbreviated as ST or STX, is one of the five languages supported by the IEC 61131-3 standard, designed for programmable logic controllers (PLCs). It is a high level language that is block structured and syntactically resembles Pascal, on which it is based. All of the languages share IEC61131 Common Elements. The variables and function calls are defined by the common elements so different languages within the IEC 61131-3 standard can be used in the same program.

<span class="mw-page-title-main">Recursion (computer science)</span> Use of functions that call themselves

In computer science, recursion is a method of solving a computational problem where the solution depends on solutions to smaller instances of the same problem. Recursion solves such recursive problems by using functions that call themselves from within their own code. The approach can be applied to many types of problems, and recursion is one of the central ideas of computer science.

The power of recursion evidently lies in the possibility of defining an infinite set of objects by a finite statement. In the same manner, an infinite number of computations can be described by a finite recursive program, even if this program contains no explicit repetitions.

In computer programming, an anonymous function is a function definition that is not bound to an identifier. Anonymous functions are often arguments being passed to higher-order functions or used for constructing the result of a higher-order function that needs to return a function. If the function is only used once, or a limited number of times, an anonymous function may be syntactically lighter than using a named function. Anonymous functions are ubiquitous in functional programming languages and other languages with first-class functions, where they fulfil the same role for the function type as literals do for other data types.

In computing, compile-time function execution is the ability of a compiler, that would normally compile a function to machine code and execute it at run time, to execute the function at compile time. This is possible if the arguments to the function are known at compile time, and the function does not make any reference to or attempt to modify any global state.

In programming languages, a label is a sequence of characters that identifies a location within source code. In most languages, labels take the form of an identifier, often followed by a punctuation character. In many high-level languages, the purpose of a label is to act as the destination of a GOTO statement. In assembly language, labels can be used anywhere an address can. Also in Pascal and its derived variations. Some languages, such as Fortran and BASIC, support numeric labels. Labels are also used to identify an entry point into a compiled sequence of statements.

The syntax and semantics of PHP, a programming language, form a set of rules that define how a PHP program can be written and interpreted.

Increment and decrement operators are unary operators that increase or decrease their operand by one.

Swift is a high-level general-purpose, multi-paradigm, compiled programming language developed by Apple Inc. and the open-source community. Swift compiles to machine code, as it is an LLVM-based compiler. Swift was first released in June 2014, and the Swift toolchain has shipped in Xcode since version 6, released in 2014.

References

  1. 1 2 "The while and do-while Statements (The Java Tutorials > Learning the Java Language > Language Basics)". Dosc.oracle.com. Retrieved 2016-10-21.
  2. "while (C# reference)". Msdn.microsoft.com. Retrieved 2016-10-21.
  3. "Chapter 3: The While programming language" (PDF). Profs.sci.univr.it. Retrieved 2016-10-21.
  4. Flemming Nielson; Hanne R. Nielson; Chris Hankin (1999). Principles of Program Analysis. Springer. ISBN   978-3-540-65410-0 . Retrieved 29 May 2013.
  5. Illingworth, Valerie (11 December 1997). Dictionary of Computing . Oxford Paperback Reference (4th ed.). Oxford University Press. ISBN   9780192800466.