Share to: share facebook share twitter share wa share telegram print page

While loop

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.

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

int x = 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 stuff
    if (someCondition)
        break;
    // more stuff
}

Demonstrating while loops

These while loops will calculate the factorial of the number 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;

APL

counter  5
factorial  1

:While counter > 0
    factorial × counter
    counter - 1
:EndWhile

  factorial

or simply

!5

AutoHotkey

counter := 5
factorial := 1

While counter > 0
    factorial *= counter--

MsgBox % factorial

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, C++

int main() {
    int count = 5;
    int factorial = 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

<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

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, 1

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

Java, C#, D

The code for the loop is the same for Java, C# and 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, 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, Oberon-07, 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.

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

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

Non-terminating while loop:

while true:
  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.

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;

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

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.

Non-terminating while loop:

while True:
    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
(define counter 5)
(define factorial 1)
(let loop ()
    (when (> counter 0)
        (set! factorial (* factorial counter))
        (set! counter (sub1 counter))
        (loop)))
(displayln factorial)

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

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

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

Ruby

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

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

puts factorial

Rust

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

    while counter > 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].
Transcript show: factorial

Swift

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

PowerShell

$counter = 5
$factorial = 1

while ($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) do
    F := F * C;
    C := C - 1;

See also

References

  1. ^ a b "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.

Read other articles:

Matty Fryatt Fryatt berseragam Leicester City pada tahun 2008Informasi pribadiNama lengkap Matthew Charles Fryatt[1]Tanggal lahir 5 Maret 1986 (umur 37)[1]Tempat lahir Nuneaton, EnglandTinggi 5 ft 10 in (1,78 m)[1]Posisi bermain PenyerangKarier junior000?–2003 WalsallKarier senior*Tahun Tim Tampil (Gol)2003–2006 Walsall 70 (27)2003–2004 → Carlisle United (pinjaman) 10 (1)2006–2011 Leicester City 168 (51)2011–2014 Hull City 82 (27)2013 ...

Чемпионат Украины по футболу 2009/2010 (молодёжное первенство) Время проведения 15 июля 2009 — 8 мая 2010 Число участников 16 Города 13 Стадионы 16 Призовые места Победитель «Карпаты» U-21 (1-й раз) Второе место «Шахтёр» U-21 Третье место «Динамо» U-21 Статистика турнира Сыграно матчей...

Уфа в годы Великой Отечественной войны — столица Башкирской АССР в годы Великой Отечественной войны и её вклад в победу над немецким нацизмом и фашизмом. Перед началом Великой Отечественной войны Уфа представляла собой город с 250 тысячным населением. Город был культур

Second president of the Watch Tower Bible and Tract Society of Pennsylvania Joseph Franklin RutherfordJoseph Franklin RutherfordBornNovember 8, 1869Versailles, Missouri, USDiedJanuary 8, 1942(1942-01-08) (aged 72)San Diego, California, USOccupationLawyerSpouseMary Malcolm FetzerChildrenMalcolm RutherfordSignature Part of a series onJehovah's Witnesses Overview Organizational structure Governing Body Watch Tower Bibleand Tract Society Corporations History Bible Student movement Leadership...

Revistas pornográficas japonesas Las revistas pornográficas, también llamadas revistas para adultos o revistas sexuales, son revistas que albergan contenido de naturaleza sexual, típicamente dentro del ámbito de la pornografía. Este tipo de publicaciones proporciona fotografías u otro tipo de ilustraciones de desnudos y actividades sexuales, habitualmente presentando individuos atractivos, tanto de género femenino como masculino. El principal objetivo de estas revistas es la de servir...

Coordenadas: 46° 44' N 1° 33' E Luant   Comuna francesa    Localização LuantLocalização de Luant na França Coordenadas 46° 44' N 1° 33' E País  França Região Centro-Vale do Loire Departamento Indre Características geográficas Área total 31,03 km² População total (2018) [1] 1 559 hab. Densidade 50,2 hab./km² Código Postal 36350 Código INSEE 36101 Luant é uma comuna francesa na região administrativa do Centro, n...

  Víbora hocicuda Estado de conservaciónVulnerable (UICN 3.1)[1]​TaxonomíaReino: AnimaliaFilo: ChordataSubfilo: VertebrataClase: SauropsidaSubclase: DiapsidaOrden: SquamataSuborden: SerpentesFamilia: ViperidaeSubfamilia: ViperinaeGénero: ViperaEspecie: V. latasteiBosca, 1878Distribución Distribución de Vipera latasti.Sinonimia Vipera latasti - Boscà, 1878[2]​ Vipera latastei - Boscà, 1879[3]​ Vipera berus aspis var. latastei - Camerano, 1889 (nomen illegiti...

داميان برودريك   معلومات شخصية الميلاد 22 أبريل 1944 (79 سنة)[1]  ملبورن  مواطنة أستراليا  الحياة العملية المدرسة الأم جامعة ديكن  المهنة روائي،  وكاتب[2][3][4]،  وكاتب خيال علمي  موظف في جامعة ملبورن  الجوائز جائزة أوريلس لأفضل رواية خيال علم...

Намібія на Олімпійських іграх Код МОК:NAM НОК:Національний олімпійськийкомітет Намібії Участь у літніх Олімпійських іграх 1992 • 1996 • 2000 • 2004 • 2008 • 2012 • 2016 • 2020 Намібія вперше взяла участь в Олімпійських іграх 1992 року у Барселоні і з тих пір не пропускала жодної літньої

United States Marine Corps general (1869–1952 Dion WilliamsBrigadier General Dion WilliamsNickname(s)Father of Marine amphibious reconnaissance[1]Born(1869-12-18)December 18, 1869Williamsburg, Ohio, U.S.DiedDecember 11, 1952(1952-12-11) (aged 82)National Naval Medical Center, Bethesda, Maryland, U.S.BuriedArlington National CemeteryAllegiance United StatesService/branch United States Marine CorpsYears of service1893–1934Rank Brigadier GeneralCommands held10th M...

Extinct genus of carnivores ProcynodictisTemporal range: 50.5–39.7 Ma PreꞒ Ꞓ O S D C P T J K Pg N early to middle Eocene lower jaw of Procynodictis vulpiceps Scientific classification Domain: Eukaryota Kingdom: Animalia Phylum: Chordata Class: Mammalia Clade: Pan-Carnivora Clade: Carnivoramorpha Clade: Carnivoraformes Genus: †ProcynodictisWortman & Matthew, 1899 Type species †Procynodictis vulpicepsWortman & Matthew, 1899 Species †P. progressus (Stock, 1935)[1]...

2018 video game developed by Frontier Developments 2018 video gameJurassic World EvolutionEuropean cover artDeveloper(s)Frontier DevelopmentsPublisher(s)Frontier DevelopmentsDirector(s)Michael BrookesProducer(s)Craig AbrahamBrendon MorganCraig SpiersDesigner(s)Andrew FletcherDan GreerArtist(s)John LawsWriter(s)John Zuur PlattenComposer(s)Jeremiah PenaSeriesJurassic ParkEngineCobra Engine Platform(s)PlayStation 4WindowsXbox OneNintendo SwitchReleasePS4, Windows, Xbox One12 June 2018Ninten...

34th Governor of Oregon For the fictional character named Barbara Millicent Roberts, see Barbie. Barbara Roberts34th Governor of OregonIn officeJanuary 14, 1991 – January 9, 1995Preceded byNeil GoldschmidtSucceeded byJohn Kitzhaber21st Secretary of State of OregonIn officeJanuary 7, 1985 – January 14, 1991GovernorVictor AtiyehNeil GoldschmidtPreceded byNorma PaulusSucceeded byPhil KeislingMember of the Oregon House of Representativesfrom the 17th districtIn o...

Regency in Indonesia Regency in Central Java, IndonesiaJepara Regency Kabupaten JeparaRegency Coat of armsMotto: Trus Karyo Tataning Bumi (Javanese: Keep working hard to build regional)Location of Jepara Regency in Central JavaCoordinates: 6°32′0″S 110°40′0″E / 6.53333°S 110.66667°E / -6.53333; 110.66667CountryIndonesiaProvinceCentral JavaCapitalJeparaGovernment • RegentEdy Suprianta (until Regent Election 2024) • Vice Regent-Ar...

Aymara winter solstice celebration Wilancha (sacrifice) in Wilaqala on Willkakuti celebrated on June 21 Willkakuti[1] (Aymara for Return of the Sun), Machaq Mara (Aymara for New Year), Mara T'aqa, Jach'a Laymi or Pacha Kuti[2] (in Spanish named Año Nuevo Andino Amazónico (Andean-Amazonic New Year)) is an Aymara celebration in Bolivia, Chile[3] and the Puno Region of Southern Peru[2] which takes place annually on 21 June, commemorating the winter solstice in t...

Unfinished, abandoned nuclear power plant in Crimea Crimean Atomic Energy StationThe unfinished unit 1 of the Crimean Atomic Energy StationCountryRussiaSoviet UnionUkraineCoordinates45°23′29″N 35°48′06″E / 45.3914°N 35.8017°E / 45.3914; 35.8017StatusCancelledOperator(s)RosatomExternal linksCommonsRelated media on Commons[edit on Wikidata] This article does not cite any sources. Please help improve this article by adding citations to ...

Species of termite Formosan termite Scientific classification Domain: Eukaryota Kingdom: Animalia Phylum: Arthropoda Class: Insecta Order: Blattodea Infraorder: Isoptera Family: Rhinotermitidae Genus: Coptotermes Species: C. formosanus Binomial name Coptotermes formosanusShiraki, 1909 Synonyms Coptotermes formosanus Shiraki, 1909 Coptotermes formosae Holmgren, 1911 Coptotermes hongkonensis Oshima, 1914 Coptotermes intrudens Oshima, 1920 Coptotermes remotus Silvestri, 1928 Coptotermes euc...

1995 American TV series or program White DwarfPromotional imageGenreScience fictionThrillerWritten byBruce WagnerDirected byPeter MarkleStarringPaul WinfieldNeal McDonoughCCH PounderBeverley MitchellDavid St. JamesEle KeatsJames MorrisonMusic byStewart CopelandCountry of originUnited StatesOriginal languageEnglishProductionExecutive producersRobert Halmi Sr.Bruce WagnerFrancis Ford CoppolaProducerDeepak NayarCinematographyPhaedon PapamichaelEditorPatrick McMahonRunning time90 minute...

Japanese manga series This article is about the manga comic. For the drama, see Skip Beat! (Taiwanese TV series). For the cardiac condition, see skipped beat. Skip Beat!Cover of the first manga volume, featuring Kyoko Mogamiスキップ・ビート!(Sukippu Bīto!)GenreComedy, coming-of-age, romance[1][2] MangaWritten byYoshiki NakamuraPublished byHakusenshaEnglish publisherNA: Viz MediaMagazineHana to YumeDemographicShōjoOriginal runFebruary 7, 2002 – presentVolu...

Austro-Hungarian Navy officer BaronGiovani (Ivan) LuppisFrigate captainBirth nameGiovanni Biagio Luppis von RammerBorn27 August 1813Fiume, Illyrian Provinces(now Rijeka, Croatia)Died11 January 1875(1875-01-11) (aged 61)Milan, Kingdom of Italy (now Italy)Allegiance Austria-HungaryService/branch Austro-Hungarian NavyBattles/warsSecond Italian War of Independence Giovanni (Ivan) Biagio Luppis Freiherr von Rammer (27 August 1813 – 11 January 1875), sometimes also known by the...

Kembali kehalaman sebelumnya