Loops/Infinite
Specifically print out "SPAM" followed by a newline in an infinite loop.
You are encouraged to solve this task according to the task description, using any language you may know.
4DOS Batch
<lang 4dos>@echo off do forever
echo SPAM
enddo</lang>
6502 Assembly
Specific OS/hardware routines for printing are left unimplemented. <lang 6502asm>InfiniteLoop LDX #0 PrintLoop: LDA MSG,x JSR PrintAccumulator ;routine not implemented INX CPX #5 BNE PrintLoop BEQ InfiniteLoop
MSG .byte "SPAM", $0A</lang>
6800 Assembly
<lang> .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 it
outs jsr outeee ;Emit a as ascii
inx ;Advance the string pointer
puts ldaa ,x ;Load a string character
bne outs ;Print it if non-null bra main ;else restart
- =====================================================;
string .as "SPAM",#13,#10,#0
.en</lang>
ACL2
<lang Lisp>(defun spam ()
(declare (xargs :mode :program)) (if nil nil (prog2$ (cw "SPAM~%") (spam))))</lang>
ActionScript
<lang actionscript>while (true) {
trace("SPAM");
}</lang>
Ada
<lang ada>loop
Put_Line("SPAM");
end loop;</lang>
Aime
<lang aime>while (1) {
o_text("SPAM\n");
}</lang>
ALGOL 68
<lang algol68>DO
printf($"SPAM"l$)
OD</lang> Or the classic "dynamic halt": <lang algol68>loop x:
printf($"SPAM"l$);
loop x</lang>
AmigaE
<lang amigae>PROC main()
LOOP WriteF('SPAM') ENDLOOP
ENDPROC</lang>
AppleScript
<lang applescript>repeat
log "SPAM"
end repeat</lang>
AutoHotkey
<lang autohotkey>Loop
MsgBox SPAM `n</lang>
AWK
<lang awk>BEGIN {
while(1) { print "SPAM" }
}</lang>
BASIC
Old-fashioned syntax: <lang qbasic>while 1
print "SPAM"
wend</lang>
Standard BASIC: <lang qbasic>do
print "SPAM"
loop</lang>
Also <lang qbasic>for i = 1 to 10 step 0
print "SPAM"
next i</lang>
10 PRINT "SPAM" 20 GOTO 10
Rather than a GOTO, instead we can use a FOR statement:
10 FOR l = 1 TO 10 STEP 0: REM A zero step makes the loop infinite 20 PRINT "SPAM" 30 NEXT l
Applesoft BASIC
<lang ApplesoftBasic>FOR I = 0 TO 1 STEP 0 : PRINT "SPAM" : NEXT</lang>
Batch File
Using goto
:
<lang dos>@echo off
- loop
echo SPAM
goto loop</lang>
Another variant which uses Windows NT's for
statement:
<lang dos>for /l %%x in (1,0,2) do @echo SPAM</lang>
This essentially is a counted loop which starts at 1
, increments by 0
and stops when the counter reaches 2
.
BBC BASIC
<lang bbcbasic> REPEAT
PRINT "SPAM" UNTIL FALSE</lang>
bc
<lang bc>while (1) "SPAM "</lang>
Befunge
Because the 2-D code space is toroidal, all loops are infinite unless explicitly stopped with @. <lang befunge>55+"MAPS",,,,,</lang>
Brainf***
<lang bf>++++++++++[->++++++>++++++++>+<<<]>+++++> [+++.---.<.>---.+++>.<]</lang>
Bracmat
<lang bracmat>whl'out$SPAM</lang>
Brat
<lang brat>loop { p "SPAM" }</lang>
C
<lang c>while(1) puts("SPAM");</lang> or <lang c> for(;;) puts("SPAM");</lang> or <lang c>do { puts("SPAM"); } while(1);</lang> or <lang c>while(puts("SPAM"));</lang>
C++
<lang cpp>while (true)
std::cout << "SPAM" << std::endl;</lang>
or <lang cpp>for (;;)
std::cout << "SPAM" << std::endl;</lang>
or <lang cpp>do
std::cout << "SPAM" << std::endl;
while (true);</lang>
C#
<lang csharp>while (true) {
Console.WriteLine("SPAM");
}</lang>
Chapel
<lang chapel>while true do writeln("SPAM");</lang>
ColdFusion
This will result in a JRun Servlet Error and heap dump.
With tags: <lang cfm><cfloop condition = "true NEQ false">
SPAM
</cfloop></lang> With script: <lang cfm><cfscript>
while( true != false ) { writeOutput( "SPAM" ); }
</cfscript></lang>
Clojure
<lang lisp>(loop [] (println "SPAM") (recur))</lang>
COBOL
<lang cobol> IDENTIFICATION DIVISION.
PROGRAM-ID. Spam.
PROCEDURE DIVISION. PERFORM UNTIL 1 <> 1 DISPLAY "SPAM" END-PERFORM
GOBACK .</lang>
OpenCOBOL supports a FOREVER
clause for PERFORM
which will have the same effect.
CoffeeScript
<lang coffeescript>loop
console.log 'SPAM'
</lang>
Common Lisp
<lang lisp>(loop (write-line "SPAM"))</lang>
D
Some common ways to create an infinite printing loop: <lang d>import std.stdio;
void main() {
while (true) writeln("SPAM");
}</lang>
<lang d>import std.stdio;
void main() {
do writeln("SPAM"); while (true);
}</lang>
<lang d>import std.stdio;
void main() {
for ( ; ; ) writeln("SPAM");
}</lang>
<lang d>import std.stdio;
void main() {
LOOP: writeln("SPAM"); goto LOOP;
}</lang>
dc
<lang dc>[[SPAM ]P dx]dx</lang>
This loop is a tail-recursive function. The program pushes the function on the stack, the outer dx makes the first call, and the inner dx makes each recursive call.
Déjà Vu
<lang dejavu>while true: !print "SPAM"</lang> Infinite recursion thanks to tail calls: <lang dejavu>labda: !print "SPAM" recurse call</lang>
Delphi
<lang Delphi>while True do Writeln('SPAM');</lang>
DWScript
<lang Delphi>while True do
PrintLn('SPAM');</lang>
E
<lang e>while (true) {
println("SPAM")
}</lang>
<lang e>def f() {
println("SPAM") f <- ()
} f <- ()</lang>
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.
Ela
Direct Approach
<lang ela>open console
loop () = writen "SPAM" $ loop!</lang>
Non-strict version
<lang ela>open console list
loop () = writen "SPAM" :: (& loop!)
take 10 <| loop! //prints SPAM only first 10 times</lang>
Erlang
<lang erlang> -module (main). -export ([main/0]).
main() ->
io:fwrite( "SPAM~n" ), main().
</lang>
Euphoria
<lang Euphoria> while 1 do
puts(1, "SPAM\n")
end while </lang>
F#
<lang fsharp> // Imperative Solution while true do
printfn "SPAM"
// Functional solution let rec forever () : unit =
printfn "SPAM" forever ()
</lang>
Factor
<lang factor>: spam ( -- ) "SPAM" print spam ;</lang> <lang factor>: spam ( -- ) [ "SPAM" print t ] loop ;</lang>
FALSE
<lang false>[1]["SPAM "]#</lang>
Fantom
<lang fantom> class Main {
public static Void main () { while (true) { echo ("SPAM") } }
} </lang>
Forth
<lang forth>: email begin ." SPAM" cr again ;</lang>
Fortran
<lang fortran> PROGRAM INFINITELOOP C While you can put this label on the WRITE statement, it is good C form to label CONTINUE statements whenever possible, rather than C statements that actually contain instructions. This way, you can C indent inside the "loop" and make it more readable.
10 CONTINUE WRITE (*,*) 'SPAM' GOTO 10
C It is also good form to close the "loop" with another label. In C this case, there is absolutely no reason to do this at all, but, C if you wanted to break, you would be able to add `GOTO 20` to C exit the loop.
20 CONTINUE
STOP END</lang>
<lang fortran>DO
WRITE(*,*) "SPAM"
END DO</lang> Although deprecated GOTO is still available <lang fortran>10 WRITE(*,*) "SPAM"
GOTO 10</lang>
Frink
<lang frink> while true
println["SPAM"]
</lang>
GAP
<lang gap>while true do
Print("SPAM\n");
od;</lang>
GML
<lang GML>while(1)
show_message("SPAM")</lang>
Go
<lang go>package main import "fmt" func main() { for { fmt.Printf("SPAM\n") } }</lang>
Groovy
<lang groovy>while (true) {
println 'SPAM'
}</lang>
Haskell
<lang haskell>forever (putStrLn "SPAM")</lang> or <lang haskell>import Control.Monad.Fix (fix) fix (putStrLn "SPAM" >>) </lang>
HicEst
<lang hicest>DO i = 1, 1E20 ! for i with 16 or more digits: i == i + 1 == loop infinite
WRITE() "SPAM"
ENDDO</lang>
Icon and Unicon
There are several ways to write infinite loops in Icon. The most straightforward would be with repeat. <lang icon>procedure main()
repeat write("SPAM")
end</lang>
Alternately one could use one of these: <lang icon>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</lang>
IDL
<lang IDL>while 1 do print,'SPAM'</lang>
Intercal
Assuming Turing Text I/O with 8-bit ASCII-compatible character set, using COME FROM:
<lang intercal> 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)</lang>
Io
<lang io>loop("SPAM" println)</lang>
J
<lang j>(-[smoutput bind 'SPAM')^:_(1)</lang>
Alternatively,
<lang j>smoutput bind 'SPAM'^:1e99 </lang>
This second 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.
Java
<lang java>while(true){
System.out.println("SPAM");
}</lang>
<lang java>for(;;){
System.out.println("SPAM");
}</lang>
JavaScript
<lang javascript>for (;;) print("SPAM");</lang> <lang javascript>while (true) print("SPAM");</lang>
Joy
<lang joy>DEFINE loop == [true []] dip while.
["SPAM\n" putchars] loop.</lang>
K
<lang K> while[1; `0:"SPAM\n"]</lang>
LabVIEW
This image is a VI Snippet, an executable image of LabVIEW 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.
Lang5
<lang lang5>do "SPAM\n" . loop</lang>
Lasso
<lang Lasso>// not wise to run this! while(1 > 0) => {^ 'SPAM\r' ^}</lang>
Liberty BASIC
<CTRL><Break> is used to terminate such loops. <lang lb> while 1
print "SPAM"
wend end </lang>
Lisaac
{ "SPAM\n".print; }.endless_loop;
Logo
<lang logo>forever [print "SPAM]</lang>
Lua
<lang lua> while true do
print("SPAM")
end
--Another solution repeat
print("SPAM")
until false </lang>
M4
<lang M4>define(`spam',`SPAM spam') spam</lang>
Make
<lang make>spam:
@echo SPAM $(MAKE)</lang>
Maple
<lang Maple> > do print(SPAM) end; </lang>
Mathematica / Wolfram Language
<lang mathematica>While[True,
Print@"SPAM"; ]</lang>
MATLAB / Octave
<lang Matlab> while (1), printf('SPAM\n'); end; </lang>
Maxima
<lang maxima>do(disp("SPAM"));</lang>
MAXScript
<lang maxscript>while true do print "SPAM\n"</lang>
Metafont
<lang metafont>forever: message "SPAM"; endfor end</lang>
МК-61/52
<lang>1 2 3 4 С/П БП 00</lang>
Note: because this device has no text output instead of "SPAM" was used the number (1234).
Modula-2
<lang modula2>LOOP
InOut.WriteString ("SPAM"); InOut.WriteLn
END;</lang>
Modula-3
<lang modula3>LOOP
IO.Put("SPAM\n");
END;</lang>
MOO
<lang moo>while (1)
player:tell("SPAM");
endwhile</lang>
MUMPS
<lang MUMPS>
FOR WRITE "SPAM",!
</lang>
Nemerle
<lang Nemerle>while (true) WriteLine("SPAM");</lang> Or, using recursion: <lang Nemerle>def loop() : void {
WriteLine("SPAM"); loop();
}</lang>
NetRexx
<lang NetRexx>/* NetRexx */ options replace format comments java crossref savelog symbols nobinary
say say 'Loops/Infinite'
loop label spam forever say 'SPAM' end spam
</lang>
Objeck
<lang objeck> while(true) {
"SPAM"->PrintLine();
}; </lang>
OCaml
<lang ocaml>while true do
print_endline "SPAM"
done</lang>
or
<lang ocaml>let rec inf_loop() =
print_endline "SPAM"; inf_loop()
in inf_loop()</lang>
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
<lang occam>#USE "course.lib" PROC main (CHAN BYTE screen!)
WHILE TRUE out.string("SPAM*c*n", 0, screen)
- </lang>
Octave
<lang octave>while(1)
disp("SPAM")
endwhile</lang>
Oz
<lang oz>for do
{Show 'SPAM'}
end</lang>
PARI/GP
<lang parigp>while(1,
print("SPAM")
);</lang>
For a shorter version, note that print
returns gnil
which is evaluated as false
. A 'cheating' solution might use print(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:
<lang parigp>until(print('SPAM),)</lang>
Pascal
<lang pascal>while true do
writeln('SPAM');</lang>
Alternatively: <lang pascal>repeat
writeln('SPAM')
until false;</lang>
Perl
<lang perl>print "SPAM\n" while 1;</lang>
Perl 6
<lang perl6>loop {
say 'SPAM';
}</lang> In addition, there are various ways of writing lazy, infinite lists in Perl 6: <lang perl6>print "SPAM\n" xx *; # repetition operator print "SPAM\n", ~* ... *; # sequence operator map {say "SPAM"}, ^Inf; # upto operator</lang>
PHP
<lang php>while(1)
echo "SPAM\n";</lang>
PicoLisp
<lang PicoLisp>(loop (prinl "SPAM"))</lang>
Pike
<lang pike>int main(){
while(1) write("SPAM\n");
}</lang>
PL/I
<lang PL/I> do forever;
put list ('SPAM'); put skip;
end; </lang>
Pop11
<lang pop11>while true do
printf('SPAM', '%p\n');
endwhile;</lang>
PostScript
<lang postscript>{}loop</lang>
PowerShell
<lang powershell>for () {
"SPAM"
}</lang>
Prolog
<lang prolog>repeat, write('SPAM'), nl, fail.</lang>
PureBasic
Repeat/Forever
<lang PureBasic>Repeat
PrintN("SPAM")
ForEver</lang>
Goto
<lang PureBasic>PrintIt: PrintN("SPAM") Goto PrintIt</lang>
Python
<lang python>while 1:
print "SPAM"</lang>
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 the False object. Any non-empty collection or string or non-zero numeric value is considered "True". However, according to Python Wiki, for Python versions 2.3+ this variant is optimized by the interpreter and thus is the fastest.
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.
<lang R>repeat print("SPAM")</lang>
Racket
<lang racket>
- lang racket
- Using recursion
(define (loop)
(displayln "SPAM") (loop))
(loop)
- Using a for loop
(for ([i (in-naturals)])
(displayln "SPAM"))
</lang>
REBOL
<lang REBOL>forever [print "SPAM"]</lang>
Retro
<lang Retro>[ "SPAM\n" puts -1 ] while</lang>
REXX
simple
<lang rexx>/*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. */</lang>
esoteric
<lang rexx>/*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. */</lang>
GO TO version
<lang rexx>/*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. */</lang>
Ruby
<lang ruby>loop {puts "SPAM"} </lang>
Run BASIC
<lang runbasic>[loop] print "Spam" :goto [loop]
while 1 print "Spam" wend</lang>
Salmon
<lang Salmon>while (true)
"SPAM"!;</lang>
Sather
<lang sather>class MAIN is
main is loop #OUT + "Spam\n"; end; end;
end;</lang>
Scala
<lang scala>while (true)
println("SPAM")</lang>
Scheme
<lang scheme>((lambda (x) (display "SPAM") (newline) (x x))
(lambda (x) (display "SPAM") (newline) (x x)))
</lang>
or, less Schemishly but with less redundancy:
<lang scheme>(do () (#f) (display "SPAM") (newline))</lang>
sed
<lang sed>:loop s/.*/SPAM/ p t loop</lang> Sed requires at least one line of input to execute, so run as follows:
echo | sed ':loop;s/.*/SPAM/;p;t loop'
Seed7
<lang seed7>$ include "seed7_05.s7i";
const proc: main is func
begin while TRUE do writeln("SPAM"); end while; end func;</lang>
Sidef
<lang ruby>{ say "SPAM!" } while(true);</lang>
Slate
<lang slate>[inform: 'SPAM'] loop</lang>
Smalltalk
<lang smalltalk>[ true ] whileTrue: [ 'SPAM' displayNl ]</lang>
SNOBOL4
<lang snobol>loop output = "SPAM" :(loop) end</lang>
SNUSP
<lang snusp>@\>@\>@\>@\>++++++++++===!/ < < < < \
| | | \M=@@@@+@+++++# \.>.>.>.>./ | | \A=@@+@@@@+++# | \P=@@+@@+@@+++# \S=@@+@+@@@+++#</lang>
Standard ML
<lang sml>while true do
print "SPAM\n";</lang>
or
<lang sml>let
fun inf_loop () = ( print "SPAM\n"; inf_loop () )
in
inf_loop ()
end</lang>
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.
SystemVerilog
<lang SystemVerilog>program main;
initial forever $display("SPAM");
endprogram </lang>
Transact-SQL
<lang sql>WHILE 1=1 BEGIN
PRINT "SPAM"
END</lang>
Tcl
<lang tcl>while true {
puts SPAM
}
- or
for {} 1 {} {
puts SPAM
}</lang>
TI-83 BASIC
There are a few ways to achieve this in TI-83 BASIC
<lang ti83b>
:Lbl 1 :Disp "SPAM :Goto 1
</lang>
Another way is by using a While loop
<lang ti83b>
:While 1 :Disp "SPAM :End
</lang>
TI-89 BASIC
<lang ti89b>Loop
Disp "SPAM"
EndLoop</lang>
TorqueScript
<lang Torque>While(1)
echo("SPAM");</lang>
Trith
<lang trith>["SPAM" print] loop</lang>
TUSCRIPT
TUSCRIPT has no infinite loop. 999999999 loops are the limit. <lang tuscript> $$ MODE TUSCRIPT LOOP/999999999 print "spam" ENDLOOP </lang>
UNIX Shell
Use any of these loops: <lang bash>while :; do echo SPAM; done</lang>
<lang bash>while true; do echo "SPAM"; done</lang>
<lang bash>until false; do echo "SPAM"; done</lang>
<lang bash>for ((;;)); do echo "SPAM"; done</lang>
C Shell
<lang bash>while (1) echo SPAM end</lang>
es
<lang es>forever {echo SPAM}</lang>
UnixPipes
<lang bash>yes SPAM</lang>
Unlambda
<lang unlambda> ``ci``s``s`kr``s``s``s``s`k.S`k.P`k.A`k.Mii</lang>
V
<lang v>true [
'SPAM' puts
] while</lang>
Vala
<lang vala>for(;;) stdout.printf("SPAM\n");</lang> <lang vala>while(true) stdout.printf("SPAM\n");</lang> <lang vala>do stdout.printf("SPAM\n"); while(true);</lang>
Vedit macro language
<lang vedit>while (1) {
Message("Spam\n")
}</lang> or: <lang vedit>do {
Message("Spam\n")
} while (1)</lang> or: <lang vedit>for (;1;) {
Message("Spam\n")
}</lang> "Nearly infinite" loop can be done by using constant ALL (=1073741824) as repeat count: <lang vedit>Repeat (ALL) {
Message("Spam\n")
}</lang>
Visual Basic
<lang vb>Do
Debug.Print("SPAM")
Loop</lang>
Visual Basic .NET
Platform: .NET
<lang vbnet>Do
Console.WriteLine("SPAM")
Loop</lang>
Wart
<lang wart>repeat :forever
prn "spam"</lang>
X86 Assembly
<lang asm> section .text global _start
_start: mov edx, len mov ecx, msg mov ebx, 1 mov eax, 4 int 0x80 jmp _start
section .data msg db "SPAM",0xa len equ $-msg </lang>
XPL0
<lang XPL0>code Text=12; loop Text(0, "SPAM ")</lang>
Z80 Assembly
Using the Amstrad CPC firmware:
<lang z80>org $4000
txt_output: equ $bb5a
start: ld hl,spam
print: ld a,(hl) cp 0 jr z,start call txt_output inc hl jr print
spam: defm "SPAM\r\n\0"</lang>
zkl
<lang zkl>while(1){println("SPAM")}</lang>