Loop constructs |
---|
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.
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)gotoLOOPSTART;
![]() | This section's factual accuracy is disputed .(November 2020) |
These example programs calculate the factorial of 5 using their respective languages' syntax for a do-while loop.
withAda.Integer_Text_IO;procedureFactorialisCounter:Integer:=5;Factorial:Integer:=1;beginloopFactorial:=Factorial*Counter;Counter:=Counter-1;exitwhenCounter=0;endloop;Ada.Integer_Text_IO.Put(Factorial);endFactorial;
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:
DimfactorialAsIntegerDimcounterAsIntegerfactorial=1counter=5Dofactorial=factorial*countercounter=counter-1LoopWhilecounter>0Printfactorial
intcounter=5;intfactorial=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]
With legacy Fortran 77 there is no DO-WHILE construct but the same effect can be achieved with GOTO:
INTEGER CNT,FACTCNT=5FACT=11CONTINUEFACT=FACT*CNTCNT=CNT-1IF(CNT.GT.0)GOTO1PRINT*,FACTEND
Fortran 90 and later supports a DO-While construct:
program FactorialProginteger::counter=5integer::factorial=1factorial=factorial*countercounter=counter-1do while(counter/=0)factorial=factorial*countercounter=counter-1end do print*,factorialend program FactorialProg
intcounter=5;intfactorial=1;do{factorial*=counter--;/* Multiply, then decrement. */}while(counter>0);System.out.println("The factorial of 5 is "+factorial);
Pascal uses repeat/until syntax instead of do while.
factorial:=1;counter:=5;repeatfactorial:=factorial*counter;counter:=counter-1;// In Object Pascal one may use dec (counter);untilcounter=0;
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.
declarecounterfixedinitial(5); declarefactorialfixedinitial(1);dountil(counter<=0);factorial=factorial*counter;counter=counter-1;end; put(factorial);
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=1counter=5whileTrue:factorial*=countercounter-=1ifcounter<1:breakprint(factorial)
In Racket, as in other Scheme implementations, a "named-let" is a popular way to implement loops:
#lang racket(definecounter5)(definefactorial1)(letloop()(set!factorial(*factorialcounter))(set!counter(sub1counter))(when(>counter0)(loop)))(displaylnfactorial)
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(factorialn)(do((countern(-counter1))(result1(*resultcounter)))((=counter0)result); Stop condition and return value.; The body of the do-loop is empty.))
| counter factorial |counter:=5.factorial:=1. [counter>0] whileTrue: [factorial:=factorial*counter.counter:=counter-1].Transcriptshow:factorialprintString
In programming language theory, lazy evaluation, or call-by-need, is an evaluation strategy which delays the evaluation of an expression until its value is needed and which also avoids repeated evaluations.
Smalltalk is a purely object oriented programming language (OOP) that was originally created in the 1970s for educational use, specifically for constructionist learning, but later found use in business. It was created at Xerox PARC by Learning Research Group (LRG) scientists, including Alan Kay, Dan Ingalls, Adele Goldberg, Ted Kaehler, Diana Merry, and Scott Wallace.
In computer programming, an infinite loop is a sequence of instructions that, as written, will continue endlessly, unless an external intervention occurs, such as turning off power via a switch or pulling a plug. It may be intentional.
In computer science, control flow is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The emphasis on explicit control flow distinguishes an imperative programming language from a declarative programming language.
Template metaprogramming (TMP) is a metaprogramming technique in which templates are used by a compiler to generate temporary source code, which is merged by the compiler with the rest of the source code and then compiled. The output of these templates can include compile-time constants, data structures, and complete functions. The use of templates can be thought of as compile-time polymorphism. The technique is used by a number of languages, the best-known being C++, but also Curl, D, Nim, and XL.
A list comprehension is a syntactic construct available in some programming languages for creating a list based on existing lists. It follows the form of the mathematical set-builder notation as distinct from the use of map and filter functions.
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.
In computer science, a for-loop or for loop is a control flow statement for specifying iteration. Specifically, a for-loop functions by running a section of code repeatedly until a certain condition has been satisfied.
REDUCE is a general-purpose computer algebra system originally geared towards applications in physics.
In computer science, a generator is a routine that can be used to control the iteration behaviour of a loop. All generators are also iterators. A generator is very similar to a function that returns an array, in that a generator has parameters, can be called, and generates a sequence of values. However, instead of building an array containing all the values and returning them all at once, a generator yields the values one at a time, which requires less memory and allows the caller to get started processing the first few values immediately. In short, a generator looks like a function but behaves like an iterator.
In computer programming, foreach loop is a control flow statement for traversing items in a collection. foreach is usually used in place of a standard for loop statement. Unlike other for loop constructs, however, foreach loops usually maintain no explicit counter: they essentially say "do this to everything in this set", rather than "do this x times". This avoids potential off-by-one errors and makes code simpler to read. In object-oriented languages, an iterator, even if implicit, is often used as the means of traversal.
In computer programming, the ternary conditional operator is a ternary operator that is part of the syntax for basic conditional expressions in several programming languages. It is commonly referred to as the conditional operator, conditional expression, ternary if, or inline if. An expression if a then b else c
or a ? b : c
evaluates to b
if the value of a
is true, and otherwise to c
. One can read it aloud as "if a then b otherwise c". The form a ? b : c
is the most common, but alternative syntax do exist; for example, Raku uses the syntax a ?? b !! c
to avoid confusion with the infix operators ?
and !
, whereas in Visual Basic .NET, it instead takes the form If(a, b, c)
.
In computer programming, conditional loops or repetitive control structures are a way for computer programs to repeat one or more various steps depending on conditions set either by the programmer initially or real-time by the actual program.
The basic control structures of Perl are similar to those used in C and Java, but they have been extended in several ways.
In computer science, recursion is a method of solving a computational problem where the solution depends on solutions to smaller instances of the same problem. Recursion solves such recursive problems by using functions that call themselves from within their own code. The approach can be applied to many types of problems, and recursion is one of the central ideas of computer science.
The power of recursion evidently lies in the possibility of defining an infinite set of objects by a finite statement. In the same manner, an infinite number of computations can be described by a finite recursive program, even if this program contains no explicit repetitions.
S-algol is a computer programming language derivative of ALGOL 60 developed at the University of St Andrews in 1979 by Ron Morrison and Tony Davie. The language is a modification of ALGOL to contain orthogonal data types that Morrison created for his PhD thesis. Morrison would go on to become professor at the university and head of the department of computer science. The S-algol language was used for teaching at the university at an undergraduate level until 1999. It was also the language taught for several years in the 1980s at a local school in St. Andrews, Madras College. The computer science text Recursive Descent Compiling describes a recursive descent compiler for S-algol, implemented in S-algol.
In the C and C++ programming languages, the comma operator is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value ; there is a sequence point between these evaluations.
The syntax and semantics of PHP, a programming language, form a set of rules that define how a PHP program can be written and interpreted.
Racket has been under active development as a vehicle for programming language research since the mid-1990s, and has accumulated many features over the years. This article describes and demonstrates some of these features. Note that one of Racket's main design goals is to accommodate creating new programming languages, both domain-specific languages and completely new languages. Therefore, some of the following examples are in different languages, but they are all implemented in Racket. Please refer to the main article for more information.