While-Schleife - While loop

Ablaufdiagramm der While-Schleife

In den meisten Programmiersprachen, eine while - Schleife ist ein Steuerflussrechnung , die Code wiederholt auf einer gegebenen Basis ausgeführt werden können Boolesche Bedingung. Die while- Schleife kann man sich als sich wiederholende if-Anweisung vorstellen .

Überblick

Das while- Konstrukt besteht aus einem Codeblock und einer Bedingung/einem Ausdruck. Die Bedingung/der Ausdruck wird ausgewertet, und wenn die Bedingung/der Ausdruck wahr ist , wird der Code in allen folgenden im Block ausgeführt. Dies wiederholt sich, bis die Bedingung/der Ausdruck falsch wird . Da die while- Schleife die Bedingung/den Ausdruck prüft, bevor der Block ausgeführt wird, wird die Kontrollstruktur oft auch als Pre-Test-Schleife bezeichnet . Vergleichen Sie dies mit der do while -Schleife , die die Bedingung/den Ausdruck testet, nachdem die Schleife ausgeführt wurde.

In der Programmiersprache C (sowie Java , C# , Objective-C und C++ , die in diesem Fall dieselbe Syntax verwenden ) beispielsweise das Codefragment

int x = 0;

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

prüft zuerst, ob x kleiner als 5 ist, was es ist, also wird der {Schleifenkörper} eingegeben, in dem die printf- Funktion ausgeführt und x um 1 erhöht wird. Nach Abschluss aller Anweisungen im Schleifenkörper wird die Bedingung ( x < 5), wird erneut geprüft und die Schleife erneut ausgeführt, wobei dieser Vorgang wiederholt wird, bis die Variable x den Wert 5 hat.

Beachten Sie, dass es möglich und in einigen Fällen wünschenswert ist, dass die Bedingung immer wahr ausgewertet wird, wodurch eine Endlosschleife erstellt wird . Wenn eine solche Schleife absichtlich erstellt wird, gibt es normalerweise eine andere Kontrollstruktur (z. B. eine break- Anweisung), die das Beenden der Schleife steuert. Zum Beispiel:

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

Demonstrieren von while- Schleifen

Diese while- Schleifen berechnen die Fakultät der Zahl 5:

ActionScript 3

var counter: int = 5;
var factorial: int = 1;

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

Printf("Factorial = %d", factorial);

Ada

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;

AutoHotkey

counter := 5
factorial := 1

While counter > 0
    factorial *= counter--    

MsgBox % factorial

Microsoft Small Basic

counter = 5    ' Counter = 5
factorial = 1  ' initial value of variable "factorial"

While counter > 0
    factorial = factorial * counter
    counter = counter - 1
    TextWindow.WriteLine(counter)
EndWhile

Visual Basic

Dim counter As Integer = 5    ' init variable and set value
Dim factorial As Integer = 1  ' initialize factorial variable

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

'Debug.Print factorial         ' Console.WriteLine(factorial) in Visual Basic .NET

Bourne (Unix)-Shell

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

echo $factorial

C oder C++

int main() {
    int counter = 5;
    int factorial = 1;

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

    printf("%d", factorial);
}

CFML

Skriptsyntax

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

writeOutput(factorial);

Tag-Syntax

<cfset counter = 5>
<cfset factorial = 1>
<cfloop condition="counter GT 1">
    <cfset factorial *= counter-->
</cfloop>
<cfoutput>#factorial#</cfoutput>

Fortran

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

gehen

Go hat keine while-Anweisung, aber die Funktion einer for-Anweisung, wenn Sie einige Elemente der for-Anweisung weglassen.

counter, factorial := 5, 1

for counter > 1 {
	counter, factorial = counter-1, factorial*counter
}

Java , C# , D

Der Code für die Schleife ist für Java, C# und D gleich:

int counter = 5;
int factorial = 1;

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

JavaScript

let counter = 5;
let factorial = 1;

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

console.log(factorial);

Lua

counter = 5
factorial = 1

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

print(factorial)

MATLAB & GNU Octave

counter = 5;
factorial = 1;

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

factorial

Mathematik

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

    factorial
]

Oberon , Oberon-2 (Programmiersprache) , Oberon-07 oder Component Pascal

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.

Eingebettete Maya-Sprache

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

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

while counter > 0:       # While counter is greater than 0
    factorial *= counter # Set new value of factorial to counter.
    dec counter          # Set the counter to counter - 1.

echo factorial

Nicht terminierende while-Schleife:

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

Pascal

Pascal hat zwei Formen der while-Schleife, while und repeat . While wiederholt eine Anweisung (es sei denn, sie ist in einem Beginn-Ende-Block eingeschlossen), solange die Bedingung wahr ist. Die repeat-Anweisung führt wiederholt einen Block von einer oder mehreren Anweisungen durch eine until- Anweisung aus und wiederholt sich weiter, es sei denn, die Bedingung ist falsch. Der Hauptunterschied zwischen den beiden besteht darin, dass die while-Schleife null Mal ausgeführt werden kann, wenn die Bedingung anfänglich falsch ist, die Wiederholungs-bis-Schleife wird immer mindestens einmal ausgeführt.

program Factorial1;
var
    Fv: integer;

    procedure fact(counter:integer);
    var
        Factorial: integer;

    begin       
         Factorial := 1;
    
         while Counter > 0 do
         begin
             Factorial := Factorial * Counter;
             Counter := Counter - 1
         end;

         WriteLn(Factorial)
     end;

begin
    Write('Enter a number to return its factorial: ');
    readln(fv);
    repeat
         fact(fv);
         Write('Enter another number to return its factorial (or 0 to quit): '); 
     until fv=0;
end.

Perl

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

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

print $factorial;

Während Schleifen häufig verwendet werden, um Daten zeilenweise (wie durch den $/Zeilentrenner definiert ) aus geöffneten Dateihandles zu lesen :

open IN, "<test.txt";

while (<IN>) {
    print;
}

close IN;

PHP

$counter = 5;
$factorial = 1;

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

echo $factorial;

PL/I

declare counter   fixed initial(5);
declare factorial fixed initial(1);

do while(counter > 0)
    factorial = factorial * counter;
    counter = counter - 1;
end;

Python

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 *= counter              # Set new value of factorial to counter.
    counter -= 1                      # Set the counter to counter - 1.

print(factorial)                      # Print the value of factorial.

Nicht terminierende while-Schleife:

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

Schläger

In Racket, wie auch in anderen Scheme- Implementierungen, ist ein Named-let eine beliebte Methode, um Schleifen zu implementieren:

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

Bei Verwendung eines Makrosystems ist die Implementierung einer while- Schleife eine triviale Übung (üblicherweise verwendet, um Makros einzuführen):

#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)

Beachten Sie jedoch, dass in Racket (wie in Scheme) oft von einem zwingenden Programmierstil abgeraten wird.

Rubin

# Calculate the factorial of 5
i = 1
factorial = 1

while i <= 5
  factorial *= i
  i += 1
end

puts factorial

Rost

fn main() {
    let mut counter = 5;
    let mut factorial = 1;

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

    println!("{}", factorial);
}

Smalltalk

Im Gegensatz zu anderen Sprachen ist eine while- Schleife in Smalltalk kein Sprachkonstrukt, sondern in der Klasse BlockClosureals Methode mit einem Parameter definiert, dem Rumpf als Abschluss , mit self als Bedingung.

Smalltalk hat auch eine entsprechende whileFalse:-Methode.

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

Schnell

var counter = 5                 // Set the initial counter value to 5 
var factorial = 1               // Set the initial factorial value to 1

while counter > 0 {             // While counter(5) is greater than 0  
    factorial *= 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

set counter 5
set factorial 1

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

puts $factorial

ÄRGERN

int counter = 5;
int factorial = 1;

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

printf("%d", factorial);

Power Shell

$counter = 5
$factorial = 1

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

$factorial

Während Programmiersprache

Die Programmiersprache While ist eine einfache Programmiersprache, die aus Zuweisungen, sequentieller Komposition, Bedingungen und while-Anweisungen aufgebaut ist und in der theoretischen Analyse der Semantik von imperativen Programmiersprachen verwendet wird .

C := 5;
F := 1;

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

Siehe auch

Verweise