Movatterモバイル変換


[0]ホーム

URL:


Jump to content
Rosetta Code
Search

Loops/Infinite

From Rosetta Code
<Loops
Task
Loops/Infinite
You are encouraged tosolve this task according to the task description, using any language you may know.
Task

Print out      SPAM       followed by a  newline   in an infinite loop.


Related tasks



11l

L   print(‘SPAM’)

360 Assembly

This for sure will result in a severe WTO buffer shortage.

INFINITE CSECT ,                       this PGM control section INFINITE AMODE 31                      addressing mode 31 bit INFINITE RMODE ANY                     loader can load either 24 or 31          BAKR  14,0                    stack caller's register contents         LR    12,15                   establish base          LA    13,0                    no savearea          USING INFINITE,12             base to assembler          LA    10,1                    1 in reg 10          LA    11,2                    2 in reg 11 LOOP     EQU   *          CR    10,11                   1==2?          BE    RETURN                  Yes, exit.         WTO    'SPAM',ROUTCDE=11       print SPAM to syslog          B     LOOP                    No, check again. RETURN   PR    ,                       return to caller         END   INFINITE

4DOS Batch

@echo offdo forever   echo SPAMenddo

6502 Assembly

Specific OS/hardware routines for printing are left unimplemented.

InfiniteLoopLDX #0PrintLoop:LDA MSG,xJSR PrintAccumulator;routine not implementedINXCPX #5BNE PrintLoopBEQ InfiniteLoopMSG.byte "SPAM", $0A

6800 Assembly

        .cr  6800        .tf  spam6800.obj,AP1        .lf  spam6800;=====================================================;;       Infinite SPAM loop for the Motorola 6800      ;;                 by barrym 2013-04-10                ;;-----------------------------------------------------;; Prints the message "SPAM" repeatedly to an ascii    ;;   terminal (console) connected to a 1970s vintage   ;;   SWTPC 6800 system, which is the target device for ;;   this assembly.                                    ;; Many thanks to:                                     ;;   swtpc.com for hosting Michael Holley's documents! ;;   sbprojects.com for a very nice assembler!         ;;   swtpcemu.com for a very capable emulator!         ;; reg x is the string pointer                         ;; reg a holds the ascii char to be output             ;;-----------------------------------------------------;outeee   =   $e1d1      ;ROM: console putchar routine        .or  $0f00;-----------------------------------------------------;main    ldx  #string    ;Point to the string        bra  puts       ;  and print itouts    jsr  outeee     ;Emit a as ascii        inx             ;Advance the string pointerputs    ldaa ,x         ;Load a string character        bne  outs       ;Print it if non-null        bra  main       ;else restart;=====================================================;string  .as  "SPAM",#13,#10,#0        .en

68000 Assembly

Hardware-specific routines for I/O are left unimplemented and just displayed as a subroutine, as this is not the focus of the task.

doSPAM:LEAMessage,A0JSRPrintStringJMPdoSPAMMessage:DC.B"SPAM",13,10,0EVEN

8080 Assembly

putsequ9org100hspam:mvic,putslxid,msgcall5jmpspammsg:db'SPAM',13,10,'$'

8086 Assembly

Works with: [DOSBox]

Loading Immediates

Spam:movah,02hmovdl,'S';VASM replaces a character in single quotes with its ascii equivalentint21h;Print Char routinemovdl,'P'int21hmovdl,'A'int21hmovdl,'M'int21hmovdl,13;Carriage Returnint21hmovdl,10;New Lineint21hjmpSpam

Loading From A Data Source

movah,02h;prep int 21h for printing to screenmovax,segSpamMessage;load into ax whatever segment the address of our message is in.movds,ax;segment registers on the original 8086 must be loaded from a registercld;clear the direction flag, this makes commands like "lodsb" auto-incrementSpamOuter:movsi,offsetSpamMessage;load the address of SpamMessage into the source indexSpamInner:lodsb;mov al,[ds:si] and increment si by 1.cmpal,0;is this the terminator?jzSpamOuter;point si to the beginning of the message againmovdl,al;the DOS interrupt for printing requires the desired character to be in DLint21h;print the chosen character to the screenjmpSpamInnerSpamMessagedb"SPAM",13,10,0

8th

One way:

:inf"SPAM\n".recurse;

Another way:

:infrepeat"SPAM\n".again;

AArch64 Assembly

Works with:as version Raspberry Pi 3B version Buster 64 bits
/* ARM assembly AARCH64 Raspberry PI 3B *//*  program infinite64.s   */ /*******************************************//* Constantes file                         *//*******************************************//* for this file see task include a file in language AArch64 assembly*/.include "../includeConstantesARM64.inc"/*********************************//* Initialized data              *//*********************************/.dataszMessage:           .asciz "SPAM\n"/*********************************//*  code section                 *//*********************************/.text.global main main: loop:    ldr x0,qAdrszMessage    bl affichageMess    b loopqAdrszMessage:     .quad szMessage/********************************************************//*        File Include fonctions                        *//********************************************************//* for this file see task include a file in language AArch64 assembly */.include "../includeARM64.inc"

ACL2

(defunspam()(declare(xargs:mode:program))(ifnilnil(prog2$(cw"SPAM~%")(spam))))

Action!

PROC Main()  DO    PrintE("SPAM")  ODRETURN
Output:

Screenshot from Atari 8-bit computer

SPAMSPAMSPAMSPAMSPAMSPAMSPAMSPAMSPAMSPAMSPAMSPAM...

ActionScript

while(true){trace("SPAM");}

Ada

loopPut_Line("SPAM");endloop;

Agena

Tested with Agena 2.9.5 Win32

do    print( "SPAM" )od

Aime

while (1) {    o_text("SPAM\n");}

ALGOL 60

Translation of:ALGOL W


Based on the 1962 Revised Repport on ALGOL:

begininteger i;for i:=1step 0until 2do      outtext("spam")end
Works with:ALGOL 60 version OS/360
'BEGIN' 'COMMENT' Loops/Infinite - Algol60 - 23/06/2018;  'INTEGER' I;  'FOR' I := 1 'STEP' 0 'UNTIL' 2 'DO'     OUTSTRING(1,'('SPAM')')'END'

ALGOL 68

DO  printf($"SPAM"l$)OD

Or the classic "dynamic halt":

loop x:   printf($"SPAM"l$);loop x

ALGOL W

begin    for i := 1 step 0 until 2 do write( "SPAM" )end.

AmigaE

PROC main()  LOOP    WriteF('SPAM')  ENDLOOPENDPROC

APL

Works with:Dyalog APL
{'SPAM'}(0)''

AppleScript

repeatlog"SPAM"endrepeat

ARM Assembly

.global mainmain:loop:    ldr r0, =message    bl printf    b loopmessage:    .asciz "SPAM\n"

ArnoldC

IT'S SHOWTIMESTICK AROUND @NO PROBLEMOTALK TO THE HAND "SPAM"CHILLYOU HAVE BEEN TERMINATED

Arturo

while[true][print"SPAM"]

Asymptote

whiletrueprint"SPAM"endwhile//Alsofor(;;){write("SPAM");}

AutoHotkey

LoopMsgBoxSPAM`n

AWK

BEGIN{while(1){print"SPAM"}}

Axe

Warning: running this program will cause you to need to reset your calculator, thereby losing any user data stored in RAM.

While 1 Disp "SPAM",iEnd

Ballerina

importballerina/io;publicfunctionmain(){whiletrue{io:println("SPAM");}}
Output:
SPAM....

BASIC

Works with:QuickBasic version 4.5

Old-fashioned syntax:

while1print"SPAM"wend

Standard BASIC:

doprint"SPAM"loop

Also

fori=1to10step0print"SPAM"nexti
Works with:Applesoft BASIC
Works with:Commodore BASIC
Works with:Tiny BASIC
Works with:ZX Spectrum Basic

The most intuitive method is to use theGOTO statement.

10print"SPAM"20goto10

Generally, usingGOSUB in place ofGOTO is incorrect. Some programming bugs come about when aGOSUB causes a potentially infinite loop, however, eventually stack memory will fill up and cause a terminating error as shown in this Commodore BASIC example:

ready.newready.10 print "spam! ";:gosub 10runspam! spam! spam! spam! spam! spam! spam! spam! spam! spam! spam! spam! spam! spam! spam! spam! spam! spam! spam! spam!spam! spam! spam! spam! spam! spam!?out of memory  error in 10ready.█

The solution is to keep the stack empty, however, this will also clear all variables used and prevent the use ofRETURNing from the "subroutine". This is accomplished with theCLEAR (orCLR in Commodore BASIC) placed at the start of the loop.

10clr:print"Commodore Spam! ";:gosub10
10clear:print"Apple Spam! ";:gosub10

Rather than aGOTO, instead we can use aFOR... NEXT statement:

10fori=1to10step0:remAzerostepmakestheloopinfinite20print"SPAM";30nexti

In most cases, we can also call theRUN command from within the program.

10print"Spam! ";20run

IF... THEN has an impliedGOTO on some BASICs...

10print"SPAM SPAM! ";:if1then10

Applesoft BASIC

FOR I = 0 TO 1 STEP 0 : PRINT "SPAM" : NEXT

BASIC256

while true    print "SPAM"end while

BBC BASIC

REPEATPRINT"SPAM"UNTILFALSE

bootBASIC

Usinggoto:

10 print "SPAM"20 goto 10

Usingrun:

10 print "SPAM"20 run

Chipmunk Basic

Works with:Chipmunk Basic version 3.6.4
10while120print"SPAM"30wend

Commodore BASIC

In addition to the general examples listed above forBASIC, there is a trick to get a Commodore BASIC program to endlessly loop its listing. All of the lines of code are a linked list in RAM. The trick is accomplished by modifying the pointer to the next line, which is recorded at the very start of each tokenized BASIC line. Instead of it pointing to the next line, you can make it point to a previous line, or itself. This will affect execution when anyGOTO orGOSUB needs to reference any line numberafter the affected line, since the line search will be corrupted (and endless...)

For example, on the Commodore 64, BASIC program storage begins at $0800 (2048) with a NULL byte, the first line begins at $0801 with the little-endian pointer to the memory address that begins the next line. After entering the short program,POKE a 1 into the low byte portion of the pointer (location $0801) causing complete pointer value to be $0801... pointing to itself. Then run or list the program for endless looping fun.

Other similarly structured BASICs based on the early Microsoft BASIC (where theLIST routine follows the linked list pointers) can be manipulated in the same manner if it is known where BASIC program memory starts.

ready.10 rem there is way too much spam in this program!20 print "spam!!";:goto 10poke 2049,1ready.runspam!!spam!!spam!!spam!!spam!!spam!!spam!!spam!!spam!!spam!!spam!!spam!!spam!!spam!!spam!!spam!!spam!!spam!!spam!!spam!!spam!!spam!!spam!!spam!!spam!!spam!!spam!!spam!!spam!!spam!!spam!!spam!!spam!!spam!!spam!!spam!!spam!!spam!!spam!!spam!!break in 10ready.list10 rem there is way too much spam in this program!10 rem there is way too much spam in this program!10 rem there is way too much spam in this program!10 rem there is way too much spam in this program!10 rem there is way too much spam in this program!10 rem there is way too much spam in this program!breakready.█

Craft Basic

doprint "SPAM"loop

FreeBASIC

' FB 1.05.0'Using Do loopDo'Alternatively this could have a conditional, "Do While 1"Print"SPAM"Loop'Using While loopWhile1Print"SPAM"Wend

Gambas

Click this link to run this code

PublicSubMain()DoPrint"SPAM"LoopEnd

GB BASIC

10 print "SPAM"20 goto10

GW-BASIC

Works with:BASICA
Works with:PC-BASIC
10WHILE120PRINT"SPAM"30WEND

Also

10PRINT"SPAM"20GOTO10

IS-BASIC

100 DO110   PRINT "SPAM"120 LOOP

Liberty BASIC

<CTRL><Break> is used to terminate such loops.

while 1  print "SPAM"wendend

MelonBasic

UsingGoto:1:

Say:"SPAM"Goto:1

UsingGoto:start:

Say:"SPAM"Goto:start

Microsoft Small Basic

WithWhile.

While "True"   TextWindow.WriteLine("SPAM")EndWhile

WithGoto.

loopStart:TextWindow.WriteLine("SPAM")Goto loopStart

Minimal BASIC

10FORI=1TO10STEP020PRINT"SPAM"30NEXTI40END

Also

10PRINT"SPAM"20GOTO1030END

MSX Basic

10FORI=1TO10STEP020PRINT"SPAM"30NEXTI

Also

10PRINT"SPAM"20GOTO10

NS-HUBASIC

UsingFOR:

10 FOR I=0 TO 1 STEP 020 PRINT "SPAM"30 NEXT

UsingGOTO:

10 PRINT "SPAM"20 GOTO 10

UsingRUN:

10 PRINT "SPAM"20 RUN

QB64

'Using Do loopDo                'Alternatively this could have a conditional, "Do While 1"     Print "SPAM"Loop'Using While loopWhile 1     Print "SPAM"Wend

Quite BASIC

10print"SPAM"20goto10

Run BASIC

[loop] print "Spam" :goto [loop]while 1print "Spam"wend

SmallBASIC

while1print"SPAM"wend

TI-83 BASIC

There are a few ways to achieve this in TI-83 BASIC

  :Lbl 1  :Disp "SPAM  :Goto 1

Another way is by using a While loop

  :While 1  :Disp "SPAM  :End

TI-89 BASIC

Loop  Disp "SPAM"EndLoop

Tiny BASIC

10PRINT"SPAM"GOTO10

True BASIC

DOPRINT"SPAM"LOOPEND

Visual Basic

DoDebug.Print("SPAM")Loop

Visual Basic .NET

Platform:.NET

Works with:Visual Basic .NET version 9.0+
DoConsole.WriteLine("SPAM")Loop

Wee Basic

let loop=1while loop=1print 1 "SPAM"wendend

XBasic

PROGRAM"Loops/Infinite"VERSION"0.0000"DECLAREFUNCTIONEntry()FUNCTIONEntry()DOPRINT"SPAM"LOOPENDFUNCTIONENDPROGRAM

Also

PROGRAM"Loops/Infinite"VERSION"0.0000"DECLAREFUNCTIONEntry()FUNCTIONEntry()WHILETRUEPRINT"SPAM"WENDENDFUNCTIONENDPROGRAM

Yabasic

do  print "SPAM"loop

Also

while true  print "SPAM"wend

Batch File

Usinggoto:

@echo off:loopecho SPAMgotoloop

Another variant which uses Windows NT'sfor statement:

Works with:Windows NT version 4 or later
for/l%%xin(1,0,2)do@echo SPAM

This essentially is a counted loop which starts at1, increments by0 and stops when the counter reaches2.

bc

while(1)"SPAM"

BCPL

get "libhdr"let start() be writes("SPAM*N") repeat

beeswax

_>`SPA`p  bN`M`<

Befunge

Because the 2-D code space is toroidal, all loops are infinite unless explicitly stopped with@.

55+"MAPS",,,,,

Binary Lambda Calculus

Adding "SPAM\n" to the BLC8 cycle program generated fromhttps://github.com/tromp/AIT/blob/master/lists/cycle.lamgives the 16 byte program

11 a1 72 34 00 2d e5 e7 ef b3 40 53 50 41 4d 0a

blz

while true    print("SPAM")end

BQN

The main way of performing an infinite loop in BQN is using recursion.

{𝕊•Out𝕩}"SPAM"

will likely end in a stack overflow.

Bracmat

whl'out$SPAM

Brainf***

Optimized for code size:

++++++++++[->++++++>++++++++>+<<<]>+++++>[+++.---.<.>---.+++>.<]

Optimized for execution speed:

10++++++++++[-> 8++++++++> 8++++++++> 6++++++> 8++++++++> 1+<<<<<]>83+++> 80> 65+++++> 77---<<<[.>.>.>.>.<<<<]

Brat

loop { p "SPAM" }

Bruijn

:import std/String .main [spam spam]spam ["SPAM\n" ++ (0 0)]

C

while(1)puts("SPAM");

or

for(;;)puts("SPAM");

or

do{puts("SPAM");}while(1);

or

while(puts("SPAM"));

or

spam:puts("SPAM");gotospam;

C#

while(true){Console.WriteLine("SPAM");}

C++

Translation of:C
while(true)std::cout<<"SPAM\n";

or

for(;;)std::cout<<"SPAM\n";

or

dostd::cout<<"SPAM\n";while(true);

C3

while(1) io::printn("SPAM");

or

for(;;) io::printn("SPAM");

or

do { io::printn("SPAM"); } while(1);

or

switch (1){  case 1:    io::printn("SPAM");    nextcase 1;}

Calcscript

(loop. (puts SPAM))

Chapel

whiletruedowriteln("SPAM");

ChucK

while(true) <<<"SPAM">>>;

Clojure

(loop[](println"SPAM")(recur))

COBOL

IDENTIFICATIONDIVISION.PROGRAM-ID.Spam.PROCEDUREDIVISION.PERFORMUNTIL1<>1DISPLAY"SPAM"END-PERFORMGOBACK.

OpenCOBOL supports aFOREVER clause forPERFORM which will have the same effect.

CoffeeScript

loopconsole.log'SPAM'

ColdFusion

This will result in a JRun Servlet Error and heap dump.

With tags:

<cfloopcondition="true NEQ false">  SPAM</cfloop>

With script:

<cfscript>while(true!=false){writeOutput("SPAM");}</cfscript>

Comal

LOOPPRINT"SPAM"ENDLOOP

Common Lisp

(loop(write-line"SPAM"))

Using DO

(do(); Not initialization(nil); Not break condition(print"SPAM")); On every loop as requested
Output:
"SPAM"...

Corescript

:topprint Spam!goto top

Cowgol

include "cowgol.coh";loop    print("Spam\n");end loop;

Crystal

loopdoputs"SPAM"end

Usingwhile/until:

whiletrueputs"SPAM"end
untilfalseputs"SPAM"end

Using an infinite range:

(0..).eachdoputs"SPAM"end

D

Some common ways to create an infinite printing loop:

importstd.stdio;voidmain(){while(true)writeln("SPAM");}
importstd.stdio;voidmain(){dowriteln("SPAM");while(true);}
importstd.stdio;voidmain(){for(;;)writeln("SPAM");}
importstd.stdio;voidmain(){LOOP:writeln("SPAM");gotoLOOP;}

Dart

main() {  while(true) {    print("SPAM");  }}

dc

[[SPAM]P dx]dx

This loop is a tail-recursive function. The program pushes the function on the stack, the outerdx makes the first call, and the innerdx makes each recursive call.

DCL

$loop:$writesys$output"SPAM"$gotoloop

Delphi

SeePascal

DIBOL-11

          START     ;Infinite Loop           RECORD  SPAM,         A4, 'SPAM'          PROC          XCALL FLAGS (0007000000,1)          ;Suppress STOP message          OPEN(8,O,'TT:')LOOP,          WRITES(8,SPAM)          GOTO LOOP          END

Draco

proc nonrec main() void:    while true do        writeln("SPAM")    odcorp

DuckDB

Works with:DuckDB version V1.0

DuckDB supports infinite loops, as for example:

with recursive cte(i) as (select 'SPAM' union all select 'SPAM' from cte) from cte;

However, as best as this author has been able to determine, this will not actually print out anythingexcept perhaps for an error message when machine resources are exhausted.

In fact, it seems that any DuckDB query which ostensibly produces an extremely large numberof outputs will actually produce none of them. In this respect, DuckDB isquite unlike its in-process analytical database system cousin, SQLite.

DWScript

whileTruedoPrintLn('SPAM');

Dyalect

while true {    print("SPAM")}

Déjà Vu

while true:!print "SPAM"

Infinite recursion thanks to tail calls:

labda:!print "SPAM"recursecall

E

while (true) {    println("SPAM")}
def f() {    println("SPAM")    f <- ()}f <- ()

The difference between these is that in the second, other activities can be interleaved with the loop; in the first, no other processing will occur in this vat.

EasyLang

while 1 = 1   print "SPAM".

EDSAC order code

The EDSAC instruction set does not include an unconditional jump: it is necessary to synthesize it by using either anE "branch on accumulator sign bit clear" orF "branch on accumulator sign bit set" order, in circumstances where the condition is guaranteed to be met. For this specific task, guaranteeing it is trivial: printing characters does not change the contents of the accumulator at all. The solution presented here, however, is more general. We use aT "transfer and clear" order to store the accumulator's contents in storage addressθ+17, then jump back to the beginning of the loop and reload the accumulator with anA "add" order. Note that the storage address used as a temporary variable should be set to zero on entry to the loop.

[ Infinite loop  =============  A program for the EDSAC  Works with Initial Orders 2 ]        T56K        GK        O10@  [ letter shift ][  1 ]  A17@  [ a += C(17@) ]        O11@        O12@        O13@        O14@        O15@        O16@        T17@  [ C(17@) = a; a = 0 ]        E1@   [ if a >= 0 goto 1@ ][ 10 ]  *F[ 11 ]  SF[ 12 ]  PF[ 13 ]  AF[ 14 ]  MF[ 15 ]  @F    [ carriage return ][ 16 ]  &F    [ line feed ][ 17 ]  PF        EZPF

Eiffel

classAPPLICATIONcreatemakefeaturemakedofromuntilfalseloopIO.put_string("SPAM%N")endendend

Ela

Direct Approach

open monad ioloop () = do  putStrLn "SPAM"  loop ()loop () ::: IO

Non-strict version

open monad ioxs = "SPAM"::xstakeit 0 _ = do return ()takeit num (x::xs) = do  putStrLn x  takeit (num - 1) xs_ = takeit 10 xs ::: IO

Elena

ELENA 6.x:

public Program(){    while (true)    {        Console.writeLine("spam")    }}

Elixir

defmoduleLoopsdodefinfinitedoIO.puts"SPAM"infiniteendendLoops.infinite

or

Stream.cycle(["SPAM"])|>Enum.each(&IO.puts&1)

Emacs Lisp

(whilet(message"SPAM"))

EMal

for ever  writeLine("SPAM")end

Erlang

-module(main).-export([main/0]).main()->io:fwrite("SPAM~n"),main().

ERRE

LOOP  PRINT("SPAM")END LOOP

You can use also WHILE TRUE..END WHILE or REPEAT...UNTIL FALSE loops.

Euphoria

while 1 do    puts(1, "SPAM\n")end while

F#

// Imperative Solutionwhiletruedoprintfn"SPAM"// Functional solutionletrecforever():unit=printfn"SPAM"forever()

Factor

Tail recursion:

:spam(--)"SPAM"printspam;

Looping combinators:

["SPAM"printt]loop
USE:combinators.extras["SPAM"print]forever

FALSE

[1]["SPAM"]#

Fantom

class Main{  public static Void main ()  {    while (true)     {      echo ("SPAM")    }  }}

Fermat

while 1 do !!'SPAM'; od

Fish

a"MAPS"ooooo

Forth

:emailbegin."SPAM"cragain;

Fortran

FORTRAN 77

10WRITE(*,*)'SPAM'GOTO10END

Fortran 90

programspamimplicit none  do    write(*,*)'SPAM'end doend programspam

Fortress

component loops_infinite  export Executable  run() = while true do    println("SPAM")  endend

Frink

while true   println["SPAM"]

FutureBasic

Loop de loop -- whose great idea was this?

include "NSLog.incl"dispatchglobal  while 1    NSLog(@"SPAM")  wenddispatchendHandleEvents

GAP

whiletruedoPrint("SPAM\n");od;

GDScript

Works with:Godot version 4.0.1
extendsMainLoopfunc_process(_delta:float)->bool:print("SPAM")returnfalse# _process loops until true is returned

GlovePIE

GlovePIE does not natively support multiple lines of output. As such, this code continuously changes the single line of output to SPAM. The below code does this without specifying an infinite loop because all GlovePIE scripts loop indefinitely until the program is stopped.

debug = "SPAM"

GML

while(1)    show_message("SPAM")

Go

packagemainimport"fmt"funcmain(){for{fmt.Printf("SPAM\n")}}

Golfscript

{"SPAM"puts 1}do

Groovy

while(true){println'SPAM'}

Halon

forever {    echo "SPAM";}

or (due to optimizations, these are equally fast)

while (true) {    echo "SPAM";}

Hare

use fmt;export fn main() void = {for (true) {fmt::println("SPAM")!;};};

Haskell

forever (putStrLn "SPAM")

or

import Control.Monad.Fix (fix)fix (putStrLn "SPAM" >>)

Haxe

while (true)  Sys.println("SPAM");

hexiscript

while true; println "SPAM"; endwhile

HicEst

DO i = 1, 1E20 ! for i with 16 or more digits:  i == i + 1 == loop infinite    WRITE() "SPAM"ENDDO

HolyC

while(1) Print("SPAM\n");

Icon andUnicon

There are several ways to write infinite loops in Icon. The most straightforward would be with repeat.

procedure main()   repeat write("SPAM")end

Alternately one could use one of these:

until &fail do write("SPAM")   # always fails, needs succeed to break...while write("SPAM")            # always succeeds, needs failure to break ...every write(|"SPAM")           # generator always succeeds, needs failure to break ...while write(|"SPAM")           # this is a common mistake that results in an endless loop...while write(1 to 5)            # a clearer version of the same mistake that generates endless 1's

IDL

while 1 do print,'SPAM'

Intercal

Assuming Turing Text I/O with 8-bit ASCII-compatible character set, using COME FROM:

       NOTE THIS IS INTERCAL       PLEASE ,1 <- #5       DO ,1 SUB #1 <- #54       DO ,1 SUB #2 <- #192       DO ,1 SUB #3 <- #136       PLEASE ,1 SUB #4 <- #208       DO ,1 SUB #5 <- #98       DO COME FROM (1)       DO READ OUT ,1(2)    DO ,1 SUB #1 <- #134(1)    PLEASE ABSTAIN FROM (2)

Io

loop("SPAM" println)

J

echo@'SPAM'F.] ''

Alternatively,

echo@'SPAM'^:1e99 ''

This implementation relies on numeric inaccuracies in IEEE floating point notation. For example, 1+1e98 is exactly equal to 1e98. That said, 1e98 iterations would still be significantly longer than the practical life of any machine anyone would care to dedicate to this task.

Or using the^:^:_. construct:

echo@'SPAM'^:1:^:_. ''

This is a clunky way of looping forever because^:_. is a special form that specifically requires that two Power conjunctions are used, i.e.f^:test^:_.; otherwise you'll get a domain error from^:. So to use this form to loop unconditionally, we need to add an otherwise pointless^:1:.

Jactl

while (true) {  println 'SPAM'}

Or:

for (;;) {  println 'SPAM'}

Janet

(forever (print "SPAM"))

Java

while (true) System.out.print("SPAM\n");
for (;;) System.out.print("SPAM\n");

JavaScript

for (;;) console.log("SPAM");
while (true) console.log("SPAM");

Joy

DEFINE loop == [true []] dip while.["SPAM\n" putchars] loop.

jq

recurse("SPAM")
Output:
"SPAM""SPAM"...

To suppress the quotation marks, invoke jq with the -r option.

Jsish

for (;;) puts('SPAM');

Julia

while true    println("SPAM")end
Output:
SPAMSPAMSPAMSPAMSPAMSPAMSPAM

and so on until ^C

K

Works with:ngn/k
{1}{`0:"SPAM"}/""
Works with:Kona
while[1; `0:"SPAM"]

Kotlin

// version 1.0.6fun main(args: Array<String>) {    while (true) println("SPAM")}

LabVIEW

This image is aVI Snippet, an executable image ofLabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code.

Lambdatalk

{def loops_infinite {lambda {}  {if true then SPAM{br} {loops_infinite} else never}}}-> loops_infinite{loops_infinite}-> SPAM forever...

Lang

loop {fn.println(SPAM)}

Lang5

do "SPAM\n" . loop

Lasso

// not wise to run this!while(1 > 0) => {^'SPAM\r'^}

LDPL

procedure:label spamdisplay "SPAM" lfgoto spam

Lily

while 1: print("SPAM")

Lingo

repeat while TRUE  put "SPAM"end repeat

Lisaac

{ "SPAM\n".print; }.endless_loop;

LiveCode

repeat forever  put "SPAM" & returnend repeat

Logo

forever [print "SPAM]

LOLCODE

HAI  CAN HAS STDIO?  IM IN YR LOOP     VISIBLE "SPAM"  IM OUTTA YR LOOPKTHXBYE

Lua

while true do  print("SPAM")end--Another solutionrepeat  print("SPAM")until false

M2000 Interpreter

All loops can stop using Esc or Ctrl+C or Break (the last two open dialog box to stop or continue). Using Escape Off we make Esc not work for breaking execution.If Esc works then Ctrl + Y (and other letters except C, A, Z, X, N, M. F, L), open Control form, which we can do: Next Step, Slow Flow, Stop, and we can show code,current stack, variables, or execute immediate statements. This works only in console, not in M2000 forms.

Module CheckIt {      Print "SPAM"      loop}Checkit

Using a Repeat (or Do) - Always block

Module CheckIt {      Repeat {            Print "SPAM"      } Always}Checkit

Printing text rendering using Report.

Module CheckIt {      \\ stop in every 2/3 of cosole lines      \\ press spacebar or mouse button to continue      Report Format$("Spam\n")      Loop}Checkit\\ using multiline string, replace report from module aboveReport {SPAM            }

M4

define(`spam',`SPAMspam')spam

MACRO11

;Infinte Loop under RT11.MCALL.PRINT.EVENBEGIN:LOOP:.PRINT #SPAMBRLOOPSPAM:.ASCIZ/SPAM/.ENDBEGIN


MAD

            VECTOR VALUES SPAM = $4HSPAM*$LOOP        PRINT FORMAT SPAM            TRANSFER TO LOOP            END OF PROGRAM

Make

spam:   @echo SPAM   $(MAKE)

Malbolge

bP&A@?>=<;:9876543210/.-,+*)('&%$T"!~}|;]yxwvutslUSRQ.yx+i)J9edFb4`_^]\yxwRQ)(TSRQ]m!G0KJIyxFvDa%_@?"=<5:98765.-2+*/.-,+*)('&%$#"!~}|utyrqvutsrqjonmPkjihgfedc\DDYAA\>>Y;;V886L5322G//D,,G))>&&A##!7~5:{y7xvuu,10/.-,+*)('&%$#"yb}|{zyxwvutmVqSohmOOjihafeHcEa`YAA\[ZYRW:U7SLKP3NMLK-I,GFED&%%@?>=6;|9y70/4u210/o-n+k)"!gg$#"!x}`{zyxZvYtsrqSoRmlkjLhKfedcEaD_^]\>Z=XWVU7S6QPON0LKDI,GFEDCBA#?"=};438y6543s1r/o-&%*k('&%e#d!~}|^z]xwvuWsVqponPlOjihgIeHcba`B^A\[ZY;W:UTSR4PI2MLKJ,,AFE(&B;:?"~<}{zz165v3s+*/pn,mk)jh&ge#db~a_{^\xwvoXsrqpRnmfkjMKg`_GG\aDB^A?[><X;9U86R53ONM0KJC,+FEDC&A@?!!6||3876w4-tr*/.-&+*)('&%$e"!~}|utyxwvutWlkponmlOjchg`edGba`_XW\?ZYRQVOT7RQPINML/JIHAFEDC&A@?>!<;{98yw5.-ss*/pn,+lj(!~ff{"ca}`^z][wZXtWUqTRnQOkNLhgfIdcFaZ_^A\[Z<XW:U8SRQPOHML/JIHG*ED=%%:?>=~;:{876w43210/(-,+*)('h%$d"ca}|_z\rqYYnsVTpoRPledLLafIGcbE`BXW??TY<:V97S64P31M0.J-+G*(DCB%@?"=<;|98765.3210p.-n+$)i'h%${"!~}|{zyxwvuXVlkpSQmlOjLbafIGcbE`BXW??TY<:V97S64P31M0.J-+G*(D'%A@?"=<}:98y6543,1r/.o,+*)j'&%eez!~a|^tsx[YutWUqjinQOkjMhJ`_dGEaDB^A?[><X;9U86R53O20LKJ-HG*ED'BA@?>7~;:{y7x5.3210q.-n+*)jh&%$#"c~}`{z]rwvutWrkpohmPkjihafI^cba`_^A\[>YXW:UTS5QP3NM0KJ-HGF?D'BA:?>=~;:z8765v32s0/.-nl$#(ig%fd"ca}|_]yrqvYWsVTpSQmPNjMKgJHdGEa`_B]\?ZY<WVUTMR5PO20LK.IHA))>CB%#?87}}49zx6wu3tr0qo-nl*ki'hf$ec!~}`{^yxwvotsrUponQlkMihKIe^]EEZ_B@\?=Y<:V97S64P31M0.J-+GFE(C&A@?8=<;:{876w43s10qo-&%kk"'hf$ec!b`|_]y\ZvYWsVTpSQmlkNiLgf_dcba`C^]\?ZY;WV97SLK33HM0.J-+G*(D'%A$">!};|z8yw543t1r/(-,+*)(i&%fd"!~}|_t]xwvutslqTonmPkjLhKIeHFbEC_^A?[TSX;9UT7R4JIN1/K.,H+)E(&B%#?"~<}{987x/4ussr).o,+l)(h&ge#db~a_{^\x[YutWrTjinQOkNLhgJeG]\aDB^]@[=SRW:877LQP3N0FEJ-+**?DC&A#98=~|:98yx/4u21rp(',mk)(ig%|{"ca}`^z][wZXtWUqTRnQOkNLhKIedcFE`YB@@?ZYRW:UTS6QPO11F..CHGF)(CB;@#>!~;XzV7gwu-QrrqMoJIkZF'WC$#AbQ`_{^L9wI64"VDConzl+j);JJ%qGFEZ~}]{ygwRuc8aSq44"H1Y.iV,e*RQ

Maple

> do print(SPAM) end;

Mathematica /Wolfram Language

While[True, Print@"SPAM"; ]

MATLAB /Octave

while true    fprintf('SPAM\n')end

Maxima

do(disp("SPAM"));

MAXScript

while true do print "SPAM\n"

Metafont

forever: message "SPAM"; endfor end

min

Works with:min version 0.19.3
(true) ("SPAM" puts!) while

Miranda

main :: [sys_message]main = repeat (Stdout "SPAM\n")

MIPS Assembly

Thanks toChibialiens.com for the header/footer, bitmap font, and print routines.

.include "\SrcAll\Header.asm".include "\SrcAll\BasicMacros.asm".include "\SrcPSX\MemoryMap.asm".include "\SrcN64\MemoryMap.asm"  CursorX equ 0x100 CursorY equ 0x101  main:la a0,MyStringjal PrintStringnopjal NewLinenopj mainnopMyString:.byte "SPAM",255,0,0,0;the 3 zeroes are padding to ensure proper alignment.;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;  MyFont:.ifdef buildn64.incbin "\ResN64\ChibiAkumas.fnt".endif.ifdef buildPSX.incbin "\ResPSX\ChibiAkumas.fnt".endif.include "\SrcALL\graphics.asm".include "..\\SrcAll\monitor.asm"  .include "\SrcN64\Footer.asm"
Output:

Screenshot of Nintendo 64 emulator

МК-61/52

1234С/ПБП00

Note: because this device has no text output instead of "SPAM" was used the number (1234).

Modula-2

LOOP  InOut.WriteString ("SPAM");  InOut.WriteLnEND;

Modula-3

LOOP  IO.Put("SPAM\n");END;

Monte

while (true):    traceln("SPAM")

MontiLang

WHILE TRUE    |SPAM| PRINT .ENDWHILE

Note thatTRUE is simply a variable equal to 1.WHILE 1, any number larger than 0 or any string with a length more than 0 would also work

MOO

while (1)  player:tell("SPAM");endwhile

MUMPS

 FOR  WRITE "SPAM",!

Nanoquery

while true    println "SPAM"end

Nemerle

while (true) WriteLine("SPAM");

Or, using recursion:

def loop() : void{    WriteLine("SPAM");    loop();}

NetRexx

/* NetRexx */options replace format comments java crossref savelog symbols nobinary  say  say 'Loops/Infinite'  loop label spam forever    say 'SPAM'    end spam

NewLISP

(while (println "SPAM"))

Nim

while true:  echo "SPAM"

Nu

loop { print SPAM }

Oberon-2 /Oberon-07

The following should work with both Oberon-2 and Oberon-07.

MODULE InfiniteLoop;IMPORT   Out;BEGIN  WHILE TRUE DO    Out.String("SPAM");Out.Ln  ENDEND InfiniteLoop.

Oberon-07 doesn't have a LOOP statement, so the following is Oberon-2 only.

MODULE InfiniteLoop;IMPORT   Out;BEGIN  LOOP    Out.String("SPAM");Out.Ln  ENDEND InfiniteLoop.

Objeck

while(true) {  "SPAM"->PrintLine();};

OCaml

while true do  print_endline "SPAM"done

or

let rec inf_loop() =      print_endline "SPAM";  inf_loop()ininf_loop()

Seen like this it looks like the "too much functional" danger when a "while" loop looks far simpler, but the functional loop may be useful to provide data to the next loop without using mutable variable.

Occam

#USE "course.lib"PROC main (CHAN BYTE screen!)  WHILE TRUE    out.string("SPAM*c*n", 0, screen):

Octave

while(1)  disp("SPAM")endwhile

Oforth

begin "SPAM" . again

Ol

(let loop ()   (display "SPAM")   (loop))

OPL

PROC main:  LOCAL loop%  loop%=1  while loop%=1  PRINT "SPAM"  ENDWHENDP

Oz

for do   {Show 'SPAM'}end

PARI/GP

while(1,  print("SPAM"));

For a shorter version, note thatprint returnsgnil which is evaluated asfalse. A 'cheating' solution might useprint(SPAM) on the hope that the variable SPAM is uninitialized and hence prints as the monomial in itself. But with the' operator that evaluation can be forced, regardless of the current value (if any) of that variable:

until(print('SPAM),)

Pascal

while true do  writeln('SPAM');

Alternatively:

repeat  writeln('SPAM')until false;

PascalABC.NET

SeePascal

Perl

while(1){    print "SPAM\n";}

or equivalently

print "SPAM\n" while 1;

Phix

whiletruedoputs(1,"SPAM\n")endwhile

Phixmonti

/# Rosetta Code problem: https://rosettacode.org/w/index.php?title=Loops/Infiniteby Galileo, 11/2022 #/true while "SPAM\n" print true endwhile

PHP

while(1)    echo "SPAM\n";

PicoLisp

(loop (prinl "SPAM"))

Pike

while(1)    write("SPAM\n");

PILOT

*TypeSpamtype:SPAMjump:*TypeSpam

Pixilang

start:fputs("SPAM\n")go start

PL/I

do forever;   put list ('SPAM'); put skip;end;

PL/M

100H:BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;DECLARE SPAM    DATA ('SPAM',0DH,0AH,'$');LOOP:  DO;        CALL PRINT( .SPAM );        GO TO LOOP;END;EOF

Plain English

WhenRepeat. appears by itself, execution proceeds from the beginning of the routine. Normally you would include a conditional statement to break or exit when a condition is met, but not in this case.

To run:Start up.Write SPAM forever.Shut down.To write SPAM forever:Write "SPAM" to the console.Repeat.

PlainTeX

Compile in console mode, with, e.g. "pdftex <file name>".

\newlinechar`\^^J\def\spam{\message{SPAM^^J}\spam}%\spam

Pluto

while true do print("SPAM") end

Pop11

while true do    printf('SPAM', '%p\n');endwhile;

PostScript

simple infinite loop:

{}loop

A bit more complex infinite loop:

/go {  /spam      { (SPAM\n) print flush }   bind def % bind and define spam  { spam } % procedure that will be executed by loop and will call spam to print  loop % the loop}%start spamming!go

PowerShell

for () {    "SPAM"}

Prolog

repeat, write('SPAM'), nl, fail.

Pure Data

Screenshot:https://i.imgur.com/IrwaafZ.png

#N canvas 426 88 450 300 10;#X obj 17 75 print;#X msg 17 55 SPAM;#X obj 17 35 metro 1;#X msg 17 15 1;#X connect 1 0 0 0;#X connect 2 0 1 0;#X connect 3 0 2 0;

Notes: the loop is started by clicking the |1(, a [loadbang] could additionally be used. An [until] object, sent a bang, will loop forever, but will hang Pure Data, whereas a high-speed metro will function perfectly.

PureBasic

Repeat/Forever

Repeat   PrintN("SPAM")ForEver

Goto

PrintIt:PrintN("SPAM")Goto PrintIt

Python

In Python 2:

while 1:   print "SPAM"

In python 3:

while 1:   print("SPAM")

Note: one can also use: "True" or any other non-false value. In Python the following values are false: 0, "" (empty string), (,) and {} and [] (empty tuples, dictionaries or lists),None (the special object), and theFalse object. Any non-empty collection or string or non-zero numeric value is considered "True". However, according toPython Wiki, for Python versions 2.3+ this variant is optimized by the interpreter and thus is the fastest.

Quackery

[ say "SPAM" cr again ]

R

Note that the default R Gui buffers outputs before pushing them to the screen. To see this run either run in terminal mode, right click on the GUI window and deselect "Buffered Output" prior to execution, or add a call to flush.console() in the loop.

repeat print("SPAM")

Racket

#lang racket;; Using recursion(define (loop)  (displayln "SPAM")  (loop))(loop);; Using a for loop(for ([i (in-naturals)])  (displayln "SPAM"))

Raku

(formerly Perl 6)

Works with:Rakudo Star version 2010.08
loop {    say 'SPAM';}

In addition, there are various ways of writing lazy, infinite lists in Raku:

print "SPAM\n" xx *;      # repetition operatorprint "SPAM\n", ~* ... *; # sequence operatormap {say "SPAM"}, ^Inf;   # upto operator

Rapira

while 1 do  output: "SPAM"od

RATFOR

program loopwhile (1==1)write(*,101)"SPAM"101 format(A)end

Rebol

forever [print "SPAM"]
until [print "SPAM" false]
while[true][print "SPAM"]

Red

forever [print "SPAM"]

Refal

$ENTRY Go { = <Prout 'SPAM'> <Go>; };

ReScript

while true {  Js.log("SPAM")}

or

let rec inf_loop = () => {  Js.log("SPAM")  inf_loop()}

Retro

[ "SPAM\n" puts -1 ] while

REXX

simple

/*REXX program displays the  word      SPAM      forever.               */  do forever  say 'SPAM'  end   /*DO forever*/                                       /*control will never reach here. */                                       /*don't stick a fork in it.      */

esoteric

/*REXX program displays the  word      SPAM      forever.               */   do  while  1==1                      /*esoteric  "forever"  clause.   */   say 'SPAM'   end   /*DO while 1==1*/                                        /*control will never reach here. */                                        /*don't stick a fork in it.      */

GO TO version

/*REXX program displays the  word      SPAM      forever.               */tell_it:    say 'SPAM'signal tell_it                         /*REXX's version of a  GO TO     */                                       /*control will never reach here. */                                       /*don't stick a fork in it.      */

too clever by half

/*REXX program displays the  word      SPAM      forever.               */  do  until  0>1                       /*too-clever-by-half forever loop*/  say 'SPAM'  end   /*DO until 0>1*/                                       /*control will never reach here. */                                       /*don't stick a fork in it.      */

Ring

while true      see "Spam"end

Robotic

This will display the wordSPAM at the bottom of the screen indefinitely:

: "infinite_loop"* "SPAM"goto "infinite_loop"

RPL

Usually in RPL, "printing" an object in RPL means putting it on top of the stack.In the present case, the loop would not be infinite since sooner or later the stack will overflow.But if the printer has an infinite paper roll, this will never stop:

≪ "SPAM"WHILE 1REPEAT PR1END ≫ EVAL

Ruby

loop {puts "SPAM"}

Rust

fn main() {    loop {        println!("SPAM");    }}

Rye

Works with:Rye version 0.0.97
forever { print "SPAM" }

S-lang

forever print("SPAM");

Salmon

while (true)    "SPAM"!;

Sather

class MAIN is  main is    loop       #OUT + "Spam\n";     end;  end;end;

Scala

while (true)  println("SPAM")

Scheme

((lambda (x) (display "SPAM") (newline) (x x)) (lambda (x) (display "SPAM") (newline) (x x)))

or, less Schemishly but with less redundancy:

(do () (#f) (display "SPAM") (newline))

Scilab

Works with:Scilab version 5.5.1
while %T    printf("SPAM\n")end
Output:
SPAMSPAMSPAMSPAM...

sed

:loops/.*/SPAM/pt loop

Sed requires at least one line of input to execute, so run as follows:

echo | sed ':loop;s/.*/SPAM/;p;t loop'

Seed7

$ include "seed7_05.s7i";const proc: main is func  begin    while TRUE do      writeln("SPAM");    end while;  end func;

Self

['SPAM' printLine] loop

SETL

program spam;    loop do        print("SPAM");    end loop;end program;

Sidef

loop { say "SPAM!" };

SIL

lblstartprintLine SPAMGOTO start

Slate

[inform: 'SPAM'] loop

Smalltalk

[    Transcript showCR:'boring stuff'.] loop[true] whileTrue:[    Transcript showCR:'also borinh'.][    Transcript showCR:'poor cpu'.] doUntil:[false][    Transcript showCR:'please press CTRL-c!'.] doWhile:[true]

SNOBOL4

loop output = "SPAM" :(loop)end

SNUSP

@\>@\>@\>@\>++++++++++===!/ < < < < \ |  |  |  \M=@@@@+@+++++# \.>.>.>.>./ |  |  \A=@@+@@@@+++# |  \P=@@+@@+@@+++# \S=@@+@+@@@+++#

Sparkling

while true {    print("SPAM");}

or

do {    print("SPAM");} while true;

or

for var b = true; b; b = true {    printf("SPAM\n");}

etc.

Spin

Works with:BST/BSTC
Works with:FastSpin/FlexSpin
Works with:HomeSpun
Works with:OpenSpin
con  _clkmode = xtal1 + pll16x  _clkfreq = 80_000_000obj  ser : "FullDuplexSerial.spin"pub main  ser.start(31, 30, 0, 115200)  repeat    ser.str(string("SPAM",13,10))  waitcnt(_clkfreq + cnt)  ser.stop  cogstop(0)

SPL

>  #.output("SPAM")<

SQL PL

Works with:Db2 LUW

version 9.7 or higher.

With SQL PL:

--#SET TERMINATOR @SET SERVEROUTPUT ON@BEGIN DECLARE I SMALLINT DEFAULT 1; WHILE (I = I) DO  CALL DBMS_OUTPUT.PUT_LINE('SPAM'); END WHILE;END @

Output:

db2 -td@db2 => SET SERVEROUTPUT ON@db2 => BEGIN...db2 (cont.) => END @DB21034E  The command was processed as an SQL statement because it was not avalid Command Line Processor command.  During SQL processing it returned:SQL20511N  There is not enough available space in the "DBMS_OUTPUT" messagebuffer.  SQLSTATE=54035SPAMSPAMSPAMSPAM...

Standard ML

while true do  print "SPAM\n";

or

let   fun inf_loop () = (    print "SPAM\n";    inf_loop ()  )in  inf_loop ()end

Seen like this it looks like the "too much functional" danger when a "while" loop looks far simpler, but the functional loop may be useful to provide data to the next loop without using mutable variable.

Stata

while 1 {        display "SPAM"}

Mata

while (1) printf("SPAM\n")

Also possible with afor loop, but unlike C, the middle expression is not optional:

for (;1;) printf("SPAM\n")

Stax

"SPAM"PG

Swift

while true {    println("SPAM")}

SystemVerilog

program main;  initial forever $display("SPAM");endprogram

TailDot

c,x,SPAM,v,x,j,3

Tailspin

'SPAM$#10;' -> \(  <> $ -> !OUT::write     $ -> #\) -> !VOID


TAV

  ?*                \ a loop without condition runs forever (unless exited by '?>')    print 'SPAM'

Tcl

while true {    puts SPAM}# orfor {} 1 {} {    puts SPAM}

TorqueScript

While(1)    echo("SPAM");

Transact-SQL

WHILE 1=1 BEGIN PRINT "SPAM"END

Trith

["SPAM" print] loop

TUSCRIPT

TUSCRIPT has no infinite loop. 999999999 loops are the limit.

$$ MODE TUSCRIPTLOOP/999999999print "spam"ENDLOOP

Uiua

⍢(&p.|1)"SPAM"

UNIX Shell

Works with:Bourne Shell

Use any of these loops:

while :; do echo SPAM; done
while true; do echo "SPAM"; done
until false; do echo "SPAM"; done
Works with:bash
Works with:ksh93
Works with:zsh
for ((;;)); do echo "SPAM"; done

C Shell

while (1)echo SPAMend

es

forever {echo SPAM}

UnixPipes

yes SPAM

Unlambda

 ``ci``s``s`kr``s``s``s``s`k.S`k.P`k.A`k.Mii

Ursa

Translation of:Python
while trueout "SPAM" endl consoleend while

Uxntal

|10 @Console/vector $2 &read $5 &type $1 &write $1 &error $1|0100&loop ;SPAM <print-str> !&loop@<print-str> ( str* -- )&whileLDAk .Console/write DEOINC2 LDAk ?&whilePOP2 JMP2r@SPAM"SPAM 0a $1

V

true [   'SPAM' puts] while

Vala

for(;;) stdout.printf("SPAM\n");
while(true) stdout.printf("SPAM\n");
do stdout.printf("SPAM\n"); while(true);

Vale

Works with:Vale version 0.2.0
import stdlib.*;exported func main() {while true {println("SPAM");}}

VAX Assembly

                               0000  0000     1 .entrymain,0                   4D415053 8F   DD  0002     2 pushl#^a"SPAM";string on stack                            5E   DD  0008     3 pushlsp;reference to string                            04   DD  000A     4 pushl#4;+length = descriptor                                     000C     5 loop:                            5E   DD  000C     6 pushlsp;descriptor by reference              00000000'GF   01   FB  000E     7 calls#1, g^lib$put_output;show message                            F5   11  0015     8 brbloop;forever                                     0017     9                                      0017    10 .endmain

VBA

Do   Debug.Print "SPAM"Loop

VBScript

Do    WScript.Echo("SPAM")Loop

Vedit macro language

while (1) {    Message("Spam\n")}

or:

do {    Message("Spam\n")} while (1)

or:

for (;1;) {    Message("Spam\n")}

"Nearly infinite" loop can be done by using constant ALL (=1073741824) as repeat count:

Repeat (ALL) {    Message("Spam\n")}

Verilog

module main;  initial     begin      forever $display("SPAM");    endendmodule

V (Vlang)

fn main() {for {print("SPAM\n")}}

Wart

repeat :forever  prn "spam"

Whenever

1 print("SPAM");1;

Wren

while (true) System.print("SPAM")

X86 Assembly

Works with:NASM version Linux
section .textglobal _start_start:mov edx, lenmov ecx, msgmov ebx, 1mov eax, 4int 0x80jmp _startsection .datamsgdb "SPAM",0xalenequ $-msg

XLISP

It is of course possible to use aWHILE loop with a condition that will always evaluate to true:

(defun keep-printing-spam ()    (while t        (display "SPAM")        (newline) ) )

Although this idiom is very common (in many programming languages), however, it feels a bit like a misuse of a looping construct that is meant to be conditional. If an unconditional jump is really what we want, then that is what we havegoto for; or rather, in XLISP we do not havegoto (in so many words) but we can achieve the effect of it using tail recursion.

(defun keep-printing-spam ()    (display "SPAM")    (newline)    (keep-printing-spam) )

XPL0

code Text=12;loop Text(0, "SPAM")

Z80 Assembly

Using the Amstrad CPC firmware:

org$4000txt_output:equ$bb5astart:ldhl,spamprint:lda,(hl)cp0jrz,startcalltxt_outputinchljrprintspam:defm"SPAM\r\n\0"

Zig

const std = @import("std");pub fn main() !void {    const stdout_wr = std.io.getStdOut().writer();    while (true) try stdout_wr.writeAll("SPAM\n");}

zkl

while(1)   { println("SPAM") }while(True){ println("SPAM") }foreach _ in ([0..]){ println("SPAM") }[0..].pump(Console.println,T(Void,"SPAM"));[0..].pump(fcn{ println("SPAM") });fcn{ println("SPAM"); return(self.fcn()) }(); // tail recursive lambda

Zoomscript

For typing:

var looploop = 1while ne loop 0print "SPAM"printlnendwhile

For importing:

¶0¶var loop¶0¶loop = 1¶0¶while ne loop 0¶1¶print "SPAM"¶1¶println¶0¶endwhile

Retrieved from "https://rosettacode.org/wiki/Loops/Infinite?oldid=395737"
Categories:
Hidden category:
Cookies help us deliver our services. By using our services, you agree to our use of cookies.

[8]ページ先頭

©2009-2026 Movatter.jp