Zatímco smyčka - While loop
Smyčkové konstrukce |
---|
Ve většině počítačových programovacích jazyků, je cyklus while je řízení toku prohlášení , které umožňuje kódu být vykonán opakovaně na základě dané booleovské stavu. Zatímco smyčka může být myšlenka jako opakující se , pokud prohlášení .
Přehled
Konstrukce while se skládá z bloku kódu a podmínky/výrazu. Vyhodnocuje se podmínka/výraz, a pokud je podmínka/výraz pravdivá , provede se kód v rámci všech jejich následujících v bloku. To se opakuje, dokud se podmínka/výraz nestane nepravdivou . Protože smyčka while kontroluje podmínku/výraz před spuštěním bloku, je řídicí struktura často také známá jako smyčka před testem . Porovnejte to se smyčkou do while , která testuje podmínku/výraz po provedení smyčky.
Například v programovacím jazyce C (stejně jako Java , C# , Objective-C a C ++ , které v tomto případě používají stejnou syntaxi ), fragment kódu
int x = 0;
while (x < 5) {
printf ("x = %d\n", x);
x++;
}
nejprve zkontroluje, zda x je menší než 5, což je, takže pak se zadá {smyčka}, kde je spuštěna funkce printf a x je zvýšeno o 1. Po dokončení všech příkazů v těle smyčky je splněna podmínka, ( x <5), je znovu zaškrtnuto a smyčka je znovu provedena, tento proces se opakuje, dokud proměnná x nemá hodnotu 5.
Všimněte si, že je možné a v některých případech žádoucí, aby podmínka byla vždy vyhodnocena jako pravdivá, a vytvořila nekonečnou smyčku . Když je taková smyčka vytvořena záměrně, obvykle existuje jiná řídicí struktura (například příkaz break ), která řídí ukončení smyčky. Například:
while (true) {
// do complicated stuff
if (someCondition)
break;
// more stuff
}
Demonstrace při smyčkách
Tyto smyčky while vypočítají faktoriál čísla 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
Shell Bourne (Unix)
counter=5
factorial=1
while [ $counter -gt 0 ]; do
factorial=$((factorial * counter))
counter=$((counter - 1))
done
echo $factorial
C nebo C ++
int main() {
int counter = 5;
int factorial = 1;
while (counter > 1)
factorial *= counter--;
printf("%d", factorial);
}
CFML
Syntaxe skriptu
counter = 5;
factorial = 1;
while (counter > 1) {
factorial *= counter--;
}
writeOutput(factorial);
Syntaxe tagu
<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
Jít
Go nemá whiile příkaz, ale má funkci příkazu for, pokud vynecháte některé prvky příkazu for.
counter, factorial := 5, 1
for counter > 1 {
counter, factorial = counter-1, factorial*counter
}
Java , C# , D
Kód pro smyčku je stejný pro Javu, C# a D:
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
Mathematica
Block[{counter=5,factorial=1}, (*localize counter and factorial*)
While[counter>0, (*While loop*)
factorial*=counter; (*Multiply*)
counter--; (*Decrement*)
];
factorial
]
Oberon , Oberon-2 (programovací jazyk) , Oberon-07 nebo 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.
Vestavěný jazyk Maya
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
Nekončící smyčka while:
while true:
echo "Help! I'm stuck in a loop!"
Pascal
Pascal má dvě formy smyčky while , while a repeat . Zatímco opakuje jedno prohlášení (pokud není uzavřeno v bloku začátku a konce), pokud je podmínka pravdivá. Příkaz opakovat opakovaně provede blok jednoho nebo více příkazů příkazem until a pokračuje v opakování, pokud podmínka není nepravdivá. Hlavním rozdílem mezi nimi je, že smyčka while se může spustit nulakrát, pokud je podmínka zpočátku nepravdivá, smyčka opakování až se vždy spustí alespoň jednou.
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;
Zatímco smyčky se často používají ke čtení dat řádek po řádku (podle definice $/
oddělovače řádků) z otevřených rukojetí souborů:
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;
Krajta
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.
Nekončící smyčka while:
while True:
print("Help! I'm stuck in a loop!")
Raketa
V raketě, stejně jako v jiných implementacích schématu , je pojmenovaný let populární způsob implementace smyček:
#lang racket
(define counter 5)
(define factorial 1)
(let loop ()
(when (> counter 0)
(set! factorial (* factorial counter))
(set! counter (sub1 counter))
(loop)))
(displayln factorial)
Pomocí makrosystému je implementace cyklu while triviální cvičení (běžně používané k zavádění maker):
#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)
Všimněte si však, že v Racket (jako ve schématu) se často nedoporučuje nutný styl programování.
Rubín
# Calculate the factorial of 5
i = 1
factorial = 1
while i <= 5
factorial *= i
i += 1
end
puts factorial
Rez
fn main() {
let mut counter = 5;
let mut factorial = 1;
while counter > 1 {
factorial *= counter;
counter -= 1;
}
println!("{}", factorial);
}
Pokec
Na rozdíl od jiných jazyků není smyčka while v Smalltalku jazykovým konstruktem, ale je definována ve třídě BlockClosure
jako metoda s jedním parametrem, tělo jako uzávěr , přičemž podmínkou je self.
Smalltalk má také odpovídající metodu whileFalse:.
| count factorial |
count := 5.
factorial := 1.
[count > 0] whileTrue:
[factorial := factorial * count.
count := count - 1].
Transcript show: factorial
Rychlý
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
VEX
int counter = 5;
int factorial = 1;
while (counter > 1)
factorial *= counter--;
printf("%d", factorial);
Prostředí PowerShell
$counter = 5
$factorial = 1
while ($counter) {
$factorial *= $counter--
}
$factorial
Zatímco programovací jazyk
Programovací jazyk While je jednoduchý programovací jazyk vytvořený z přiřazení, sekvenční kompozice, podmíněností a příkazů while, který se používá v teoretické analýze sémantiky imperativního programovacího jazyka .
C := 5;
F := 1;
while (C > 1) do
F := F * C;
C := C - 1;
Viz také
- Do while
- Pro smyčku
- Pro každého
- LOOP (programovací jazyk) - programovací jazyk s vlastností, že funkce, které dokáže vypočítat, jsou přesně ty primitivní rekurzivní funkce