Do while loop

Do While loop flow diagram

In many 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.

The do while construct consists of a process symbol and a condition. First the code within the block is executed. Then the condition is evaluated. If the condition is true the code within the block is executed again. This repeats until the condition becomes false.

Do while loops check the condition after the block of code is executed. This control structure can be known as a post-test loop. This means the do-while loop is an exit-condition loop. However a while loop will test the condition before the code within the block is executed.

This means that the code is always executed first and then the expression or test condition is evaluated. This process is repeated as long as the expression evaluates to true. If the expression is false the loop terminates. A while loop sets the truth of a statement as a necessary condition for the code's execution. A do-while loop provides for the action's ongoing execution until the condition is no longer true.

It is possible and sometimes desirable for the condition to always evaluate to be true. This creates an infinite loop. When an infinite loop is created intentionally there is usually another control structure that allows termination of the loop. For example, a break statement would allow termination of an infinite loop.

Some languages may use a different naming convention for this type of loop. For example, the Pascal and Lua languages have a "repeat until" loop, which continues to run until the control expression is true and then terminates. In contrast a "while" loop runs while the control expression is true and terminates once the expression becomes false.

Equivalent constructs

do {
    do_work();
} while (condition);

is equivalent to

do_work();

while (condition) {
    do_work();
}

In this manner, the do ... while loop saves the initial "loop priming" with do_work(); on the line before the while loop.

As long as the continue statement is not used, the above is technically equivalent to the following (though these examples are not typical or modern style used in everyday computers):

while (true) {
   do_work();
   if (!condition) break;
}

or

LOOPSTART:
    do_work();
    if (condition) goto LOOPSTART;

Demonstrating do while loops

These example programs calculate the factorial of 5 using their respective languages' syntax for a do-while loop.

Ada

with Ada.Integer_Text_IO;

procedure Factorial is
    Counter   : Integer := 5;
    Factorial : Integer := 1;
begin
    loop
        Factorial := Factorial * Counter;
        Counter   := Counter - 1;
        exit when Counter = 0;
    end loop;

    Ada.Integer_Text_IO.Put (Factorial);
end Factorial;

BASIC

Early BASICs (such as GW-BASIC) used the syntax WHILE/WEND. Modern BASICs such as PowerBASIC provide both WHILE/WEND and DO/LOOP structures, with syntax such as DO WHILE/LOOP, DO UNTIL/LOOP, DO/LOOP WHILE, DO/LOOP UNTIL, and DO/LOOP (without outer testing, but with a conditional EXIT LOOP somewhere inside the loop). Typical BASIC source code:

Dim factorial As Integer
Dim counter As Integer

factorial = 1
counter = 5

Do
    factorial = factorial * counter
    counter = counter - 1
Loop While counter > 0

Print factorial

C, C++, D

int counter = 5;
int factorial = 1;

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

printf("factorial of 5 is %d\n", factorial);

Do-while(0) statements are also commonly used in C macros as a way to wrap multiple statements into a regular (as opposed to compound) statement. It makes a semicolon needed after the macro, providing a more function-like appearance for simple parsers and programmers as well as avoiding the scoping problem with if. It is recommended in CERT C Coding Standard rule PRE10-C.[1]

Fortran

With legacy Fortran 77 there is no DO-WHILE construct but the same effect can be achieved with GOTO:

      INTEGER CNT,FACT
      CNT=5
      FACT=1
    1 CONTINUE
      FACT=FACT*CNT
      CNT=CNT-1
      IF (CNT.GT.0) GOTO 1
      PRINT*,FACT
      END

Fortran 90 and later does not have a do-while construct either, but it does have a while loop construct which uses the keywords "do while" and is thus actually the same as the for loop.[2]

program FactorialProg
    integer :: counter = 5
    integer :: factorial = 1

    factorial = factorial * counter
    counter = counter - 1

    do while (counter > 0) ! Truth value is tested before the loop
        factorial = factorial * counter
        counter = counter - 1
    end do

    print *, factorial
end program FactorialProg

Java

int counter = 5;
int factorial = 1;

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

System.out.println("The factorial of 5 is " + factorial);

Pascal

Pascal uses repeat/until syntax instead of do while.

factorial := 1;
counter := 5;
repeat
   factorial := factorial * counter;
   counter := counter - 1; // In Object Pascal one may use dec (counter);
until counter = 0;

PL/I

The PL/I DO statement subsumes the functions of the post-test loop (do until), the pre-test loop (do while), and the for loop. All functions can be included in a single statement. The example shows only the "do until" syntax.

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

do until(counter <= 0);
    factorial = factorial * counter;
    counter = counter - 1;
end;

put(factorial);

Python

Python does not have a DO-WHILE loop, but its effect can be achieved by an infinite loop with a breaking condition at the end.

factorial = 1
counter = 5

while True:
    factorial *= counter
    counter -= 1
    if counter < 1:
        break

print(factorial)

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 ()
    (set! factorial (* factorial counter))
    (set! counter (sub1 counter))
    (when (> counter 0) (loop)))
(displayln factorial)

Compare this with the first example of the while loop example for Racket. Be aware that a named let can also take arguments.

Racket and Scheme also provide a proper do loop.

(define (factorial n)
    (do ((counter n (- counter 1))
        (result 1 (* result counter)))
    ((= counter 0) result) ; Stop condition and return value.
    ; The body of the do-loop is empty.
    ))

Smalltalk

| counter factorial |
counter := 5.
factorial := 1.

[counter > 0] whileTrue:
    [factorial := factorial * counter.
    counter := counter - 1].

Transcript show: factorial printString

See also

References

  1. ^ "C multi-line macro: do/while(0) vs scope block". Stack Overflow.
  2. ^ "Microsoft visual basic". msdn.microsoft.com. Retrieved 21 January 2016.

Read other articles:

Apel kerdil Klasifikasi ilmiah Kerajaan: Plantae (tanpa takson): Angiospermae (tanpa takson): Eudicot (tanpa takson): Rosid Ordo: Myrtales Famili: Myrtaceae Genus: Angophora Spesies: A. hispida Nama binomial Angophora hispida[1](Sm.) Blaxell Sinonim Eucalyptus hispida (Sm.) BrookerAngophora cordifolia Cav. Angophora hispida tumbuh sebagai mallee, atau sebagai pohon dengan tinggi sekitar 7 m (25 kaki).[2] Ukuran kecil A. hispida, khususnya ketika dibandingkan de...

 

 

Political movement in Cornwall, England Part of a series on the History of Cornwall History Timeline History of Cornwall Cornish devolution Medieval kingdom Dumnonia Dumnonii Cornovii Rulers (or titles) Legendary rulers King of Cornwall Duke of Cornwall Feudal Baronies Law Cornish Stannary Parliament Stannary law Modern governance Cornwall Council Proposed Cornish Assembly Local history Truro Topics Cornish language Cornish literature Music history Mining Geological history  Cornwall ...

 

 

Walled village in Sha Tin District, Hong Kong This article is about the village in Sha Tin District. For the village in Yuen Long District, see Tai Wai Tsuen (Yuen Long District). For other uses, see Tai Wai (disambiguation). Aerial view of Tai Wai Village, surrounded by some of the modern developments of Tai Wai. Entrance gate of Tai Wai Village. Hau Wong Temple within Tai Wai Village. Wai ancestral hall within Tai Wai Village. Former Tai Wai Public School [zh] in Tai Wai Villag...

44-я церемония вручения наград премии «Золотой глобус» 31 января 1987 года Лучший фильм (драма): «Взвод» Лучший фильм (комедия или мюзикл): «Ханна и её сёстры» Лучший драматический сериал: «Закон Лос-Анджелеса» Лучший сериал (комедия или мюзикл): «Золотые девочки» Лучший мини-...

 

 

This article is about Southampton suburb. For people with the surname, see Freemantle (surname). For other uses, see Fremantle (disambiguation). Human settlement in EnglandFreemantleChrist Church, FreemantleFreemantleLocation within SouthamptonUnitary authoritySouthamptonCeremonial countyHampshireRegionSouth EastCountryEnglandSovereign stateUnited KingdomPost townSOUTHAMPTONPostcode districtSO15Dialling code023PoliceHampshire and Isle of WightFireHampshire and Isle of...

 

 

Model miniatur istana (utara di sisi kiri) Istana Kekaisaran Kyoto (京都御所code: ja is deprecated , Kyoto-gosho) adalah bekas istana pemerintahan Kekaisaran Jepang. Para Kaisar bermukim di Istana Kekaisaran Tokyo setelah Restorasi Meiji pada 1869, dan preservasi Istana Kekaisaran Kyoto diperintahkan pada 1877. Saat ini halamannya dibuka untuk umum, dan Badan Rumah Tangga Kekaisaran mentuanrumahi pariwisata umum ke bangunan tersebut beberapa kali dalam sehari. Pranala luar Wikimedia Commo...

Referendum abrogativo in Italia del 1974Stato Italia Data12 e 13 maggio 1974 Tipoabrogativo Esito Sì    40,7% No    59,3% Quorum raggiunto Affluenza87,72% Risultati per provincia     Sì      No Il referendum abrogativo in Italia del 1974 si tenne il 12 e 13 maggio ed ebbe come oggetto la disciplina normativa con cui era stato introdotto l'istituto del divorzio, previsto dalla «legge 1º dicembre 1970, n. 898�...

 

 

谢赫·穆吉布·拉赫曼Sheikh Mujibur Rahmanশেখ মুজিবুর রহমান第1任孟加拉總統任期1971年4月11日—1972年1月12日总理塔杰丁·艾哈迈德前任首任继任Nazrul Islam (Acting)任期1975年1月25日—1975年8月15日总理Muhammad Mansur Ali前任Mohammad Mohammadullah继任孔达卡尔·穆什塔克·艾哈迈德第2任孟加拉總理任期1972年1月12日—1972年1月24日总统阿布·赛义德·乔杜里Mohammad Mohammadullah前任Tajud...

 

 

Provincial government of Sindh, Pakistan Government of SindhProvincial Government SealProvincial Government FlagSeat of government KarachiLegislatureAssemblySindh AssemblySpeakerAwais Qadir ShahMembers168 [1]ExecutiveGovernorKamran Tessori[2]Chief SecretaryDr. Muhammad Fakhre Alam [3]Chief MinisterMurad Ali Shah [4]JudiciaryHigh CourtSindh High CourtChief justice of High CourtAqeel Ahmed AbbasiWebsitewww.sindh.gov.pk The Government of Sindh (Sindhi: حڪو...

Questa voce è parte della serie Storia della Puglia Voci principali Apulia Iapigia Iapigi Dauni Peuceti Messapi Lingua messapica Muro Tenente Magna Grecia Regio II Apulia et Calabria Apulia et Calabria Egnazia Capitanata Terra di Bari Terra d'Otranto Principato di Taranto Storia del Gargano Storia del Salento Mappa di Soleto Battaglia di Canne Disfida di Barletta Battaglia di Troia Battaglia di Ruvo Battaglia di Cerignola Battaglia di Bitonto Notte di Taranto Fuga di Vittorio Emanuele III S...

 

 

Частина серії проФілософіяLeft to right: Plato, Kant, Nietzsche, Buddha, Confucius, AverroesПлатонКантНіцшеБуддаКонфуційАверроес Філософи Епістемологи Естетики Етики Логіки Метафізики Соціально-політичні філософи Традиції Аналітична Арістотелівська Африканська Близькосхідна іранська Буддій�...

 

 

Частина серії проФілософіяLeft to right: Plato, Kant, Nietzsche, Buddha, Confucius, AverroesПлатонКантНіцшеБуддаКонфуційАверроес Філософи Епістемологи Естетики Етики Логіки Метафізики Соціально-політичні філософи Традиції Аналітична Арістотелівська Африканська Близькосхідна іранська Буддій�...

Anglican church in Ireland Church of IrelandEaglais na hÉireann (Irish)Kirk o Airlann (Scots)Holmpatrick St Patrick Church in Skerries, County DublinTypeCommunionClassificationProtestantOrientationAnglican[a]ScriptureBibleTheologyAnglican doctrinePolityEpiscopalPrimatesArchbishop of Armagh – John McDowell Archbishop of Dublin – Michael JacksonAssociationsAnglican CommunionConference of European ChurchesChurches Together in Britain and IrelandIrish Council of ChurchesPor...

 

 

Region of Gaul between the Seine and Loire rivers This article is about the historic region. For other uses, see Armorica (disambiguation). The Roman geographical area of Armorica. The Seine and the Loire are marked in red. In ancient times, Armorica or Aremorica (Gaulish: Aremorica; Breton: Arvorig [arˈvoːrik]; French: Armorique [aʁmɔʁik]) was a region of Gaul between the Seine and the Loire that includes the Brittany Peninsula, extending inland to an indeterminate point...

 

 

American Samoa affiliate of the Democratic Party American Samoa Democratic Party ChairpersonTi’a ReidVice ChairpersonPetti MatilaSecretaryRenee Togafau Mata’utiaNational CommitteewomanSandra King-YoungNational CommitteemanAndrew BerquistTreasurerJustin TuiasosopoHeadquartersP.O. Box 1281, Pago Pago, AS 96799IdeologyModern liberalismNational affiliationDemocratic PartyColors  BlueWebsiteasdems.comPolitics of American SamoaPolitical partiesElections American Samoa Democratic Party is t...

Non-metropolitan district in EnglandBorough of MaidstoneNon-metropolitan districtJubilee Square, MaidstoneMaidstone shown within KentCoordinates: 51°16′24″N 0°31′20″E / 51.27333°N 0.52222°E / 51.27333; 0.52222Sovereign stateUnited KingdomConstituent countryEnglandRegionSouth East EnglandNon-metropolitan countyKentStatusNon-metropolitan districtAdmin HQMaidstoneIncorporated1 April 1974Government • TypeNon-metropolitan district council •&#...

 

 

هذه المقالة يتيمة إذ تصل إليها مقالات أخرى قليلة جدًا. فضلًا، ساعد بإضافة وصلة إليها في مقالات متعلقة بها. (أكتوبر 2019) لورا بارتون معلومات شخصية الميلاد سنة 1977 (العمر 46–47 سنة)  مواطنة المملكة المتحدة  الحياة العملية المهنة صحافية،  وروائية،  وصحفية الموسيقى  �...

 

 

1959 experimental VTOL aircraft model Avrocar redirects here. For the band, see Avrocar (band). VZ-9 Avrocar The Avrocar S/N 58-7055 (marked AV-7055) on its rollout. Role Proof of concept VTOL experimental aircraftType of aircraft National origin Canada Manufacturer Avro Canada Designer John Frost First flight 12 November 1959 Introduction 1958 Retired 1961 Primary users United States Air Force (intended)United States Army (intended) Produced 1958–1959 Number built 2 The Avro Canada VZ...

Part of a series on theNation of Islam Influencers Satokata Takahashi Noble Drew Ali Leaders Wallace Fard Muhammad Elijah Muhammad Malcolm X Warith Deen Mohammed Louis Farrakhan Tynnetta Muhammad Ishmael Muhammad Ava Muhammad David Muhammad James 3X Khalid Muhammad Beliefs and theology Saviours' Day Nation of Islam and antisemitism Tribe of Shabazz Yakub History Million Man March Millions More Movement Justice or Else Publications A Torchlight for America The Final Call Muhammad Speaks How to...

 

 

Overview of Estonian neopaganism The Jumiõis, symbol of Taaraism and Maausk used as the official logo of Maavalla Koda. Estonian neopaganism, or the Estonian native faith, spans various contemporary revivals of the indigenous religion of the Estonian people, adapted from their local myths and culture.[1] Major branches include Taaraism (Estonian: taarausk literally Taara faith), a monistic faith based on the god Tharapita founded as a national religion in 1928; and Maausk (Estonian: ...