Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

While loop

From Wikipedia, the free encyclopedia
Control flow statement for repeating execution until a condition is met
This articleneeds additional citations forverification. Please helpimprove this article byadding citations to reliable sources. Unsourced material may be challenged and removed.
Find sources: "While loop" – news ·newspapers ·books ·scholar ·JSTOR
(October 2016) (Learn how and when to remove this message)
While loop flow diagram
Loop constructs

In most computerprogramming languages, awhile loop is acontrol flowstatement that allows code to be executed repeatedly based on a givenBoolean condition. Thewhile loop can be thought of as a repeatingif statement.

Overview

[edit]

Thewhile construct consists of a block of code and a condition/expression.[1] The condition/expression is evaluated, and if the condition/expression istrue,[1] the code within all of their following in the block is executed. This repeats until the condition/expression becomesfalse. Because thewhile loop checks the condition/expression before the block is executed, the control structure is often also known as apre-test loop. Compare this with thedo while loop, which tests the condition/expressionafter the loop has executed.

For example, in the languagesC,Java,C#,[2]Objective-C, andC++, (whichuse 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 theprintf 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 thevariable x has the value 5.

It is possible, and in some cases desirable, for the condition toalways evaluate to true, creating aninfinite loop. When such a loop is created intentionally, there is usually another control structure (such as abreak statement) that controls termination of the loop.For example:

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

Demonstratingwhile loops

[edit]

Thesewhile loops will calculate thefactorial of the number 5:

ActionScript 3

[edit]
Further information:ActionScript 3.0
varcounter:int=5;varfactorial:int=1;while(counter>1){factorial*=counter;counter--;}Printf("Factorial = %d",factorial);

Ada

[edit]
Further information:Ada (programming language)
The WikibookAda_Programming has a page on the topic of:Control
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

[edit]
Further information:APL (programming language)
counter5factorial1:Whilecounter>0factorial×countercounter-1:EndWhilefactorial

or simply

!5

AutoHotkey

[edit]
Further information:AutoHotkey
counter:=5factorial:=1Whilecounter>0factorial*=counter--MsgBox%factorial

Small Basic

[edit]
Further information:Microsoft Small Basic
counter=5' Counter = 5factorial=1' initial value of variable "factorial"Whilecounter>0factorial=factorial*countercounter=counter-1TextWindow.WriteLine(counter)EndWhile

Visual Basic

[edit]
Further information: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

[edit]
Further information:Bourne shell
counter=5factorial=1while[$counter-gt0];dofactorial=$((factorial*counter))counter=$((counter-1))doneecho$factorial

C, C++

[edit]
Further information:C (programming language) andC++
intmain(){intcount=5;intfactorial=1;while(count>1)factorial*=count--;printf("%d",factorial);}

ColdFusion Markup Language (CFML)

[edit]
Further information:ColdFusion Markup Language

Script syntax

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

Tag syntax

[edit]
Further information:Tag (programming)
<cfsetcounter=5><cfsetfactorial=1><cfloopcondition="counter GT 1"><cfsetfactorial*=counter--></cfloop><cfoutput>#factorial#</cfoutput>

Fortran

[edit]
Further information:Fortran
programFactorialProginteger::counter=5integer::factorial=1do while(counter>0)factorial=factorial*countercounter=counter-1end do    print*,factorialend programFactorialProg

Go

[edit]
Further information:Go (programming language)

Go has nowhile statement, but it has the function of afor statement when omitting some elements of thefor statement.

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

Java, C#, D

[edit]
Further information:Java (programming language),C Sharp (programming language), andD (programming language)

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

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

JavaScript

[edit]
Further information:JavaScript
letcounter=5;letfactorial=1;while(counter>1)factorial*=counter--;console.log(factorial);

Lua

[edit]
Further information:Lua (programming language)
counter=5factorial=1whilecounter>0dofactorial=factorial*countercounter=counter-1endprint(factorial)

MATLAB, Octave

[edit]
Further information:MATLAB andGNU Octave
counter=5;factorial=1;while(counter>0)factorial=factorial*counter;%Multiplycounter=counter-1;%Decrementendfactorial

Mathematica

[edit]
Further information:Wolfram Mathematica andWolfram Language
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

[edit]
Further information:Oberon (programming language),Oberon-2,Oberon-07, andComponent 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

[edit]
Further information: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

[edit]
Further information:Nim (programming language)
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

[edit]
Further information:Pascal (programming language)

Pascal has two forms of the while loop,while andrepeat. 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 anuntil 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

[edit]
Further information: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

[edit]
Further information:PHP
$counter=5;$factorial=1;while($counter>0){$factorial*=$counter--;// Multiply, then decrement.}echo$factorial;

PL/I

[edit]
Further information:PL/I
declarecounterfixedinitial(5);declarefactorialfixedinitial(1);dowhile(counter>0)factorial=factorial*counter;counter=counter-1;end;

Python

[edit]
Further information:Python (programming language)
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

[edit]
Further information:Racket (programming language) andScheme (programming language)

In Racket, as in otherScheme implementations, anamed-let is a popular way to implement loops:

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

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

#langracket(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

[edit]
Further information:Ruby (programming language)
# Calculate the factorial of 5i=1factorial=1whilei<=5factorial*=ii+=1endputsfactorial

Rust

[edit]
Further information:Rust (programming language)
fnmain(){letmutcounter=5;letmutfactorial=1;whilecounter>1{factorial*=counter;counter-=1;}println!("{}",factorial);}

Smalltalk

[edit]
Further information:Smalltalk

Contrary to other languages, in Smalltalk awhile loop is not alanguage construct but defined in the classBlockClosure as a method with one parameter, the body as aclosure, 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

[edit]
Further information:Swift (programming language)
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

[edit]
Further information:Tcl
setcounter5setfactorial1while{$counter>0}{setfactorial[expr$factorial*$counter]incrcounter-1}puts$factorial

VEX

[edit]
Further information:VEX prefix
intcounter=5;intfactorial=1;while(counter>1)factorial*=counter--;printf("%d",factorial);

PowerShell

[edit]
Further information:PowerShell
$counter=5$factorial=1while($counter){$factorial*=$counter--}$factorial

While (language)

[edit]

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

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

See also

[edit]

References

[edit]
  1. ^ab"The while and do-while Statements (The Java Tutorials > Learning the Java Language > Language Basics)".Dosc.oracle.com. Retrieved2016-10-21.
  2. ^"while (C# reference)".Msdn.microsoft.com. Retrieved2016-10-21.
  3. ^"Chapter 3: The While programming language"(PDF).Profs.sci.univr.it. Retrieved2016-10-21.
  4. ^Flemming Nielson; Hanne R. Nielson; Chris Hankin (1999).Principles of Program Analysis. Springer.ISBN 978-3-540-65410-0. Retrieved29 May 2013.
  5. ^Illingworth, Valerie (11 December 1997).Dictionary of Computing. Oxford Paperback Reference (4th ed.). Oxford University Press.ISBN 9780192800466.
Retrieved from "https://en.wikipedia.org/w/index.php?title=While_loop&oldid=1277722304"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp