Loops/Infinite
You are encouraged to solve this task according to the task description, using any language you may know.
[edit] 4DOS Batch
@echo off
do forever
echo SPAM
enddo
[edit] 6502 Assembly
Specific OS/hardware routines for printing are left unimplemented.
InfiniteLoop LDX #0
PrintLoop: LDA MSG,x
JSR PrintAccumulator ;routine not implemented
INX
CPX #5
BNE PrintLoop
BEQ InfiniteLoop
MSG .byte "SPAM", $0A
[edit] 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 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
[edit] ACL2
(defun spam ()
(declare (xargs :mode :program))
(if nil
nil
(prog2$ (cw "SPAM~%")
(spam))))
[edit] ActionScript
while (true) {
trace("SPAM");
}
[edit] Ada
loop
Put_Line("SPAM");
end loop;
[edit] Aime
while (1) {
o_text("SPAM\n");
}
[edit] ALGOL 68
DO
printf($"SPAM"l$)
OD
Or the classic "dynamic halt":
loop x:
printf($"SPAM"l$);
loop x
[edit] AmigaE
PROC main()
LOOP
WriteF('SPAM')
ENDLOOP
ENDPROC
[edit] AppleScript
repeat
log "SPAM"
end repeat
[edit] AutoHotkey
Loop
MsgBox SPAM `n
[edit] AWK
BEGIN {
while(1) {
print "SPAM"
}
}
[edit] BASIC
Old-fashioned syntax:
WHILE 1
PRINT "SPAM"
WEND
Standard BASIC:
DO
PRINT "SPAM"
LOOP
Also
FOR i = 1 TO 10 STEP 0
PRINT "SPAM"
NEXT i
With classic (minimal) BASIC, the standard way to make an infinite loop would be:
10 PRINT "SPAM" 20 GOTO 10
We can also use a loop, rather than a jump:
10 FOR l = 1 TO 10 STEP 0: REM A zero step makes the loop infinite 20 PRINT "SPAM" 30 NEXT l
[edit] Batch File
Using goto:
@echo off
:loop
echo SPAM
goto loop
Another variant which uses Windows NT's for statement:
for /l %%x in (1,0,2) do @echo SPAM
This essentially is a counted loop which starts at 1, increments by 0 and stops when the counter reaches 2.
[edit] BBC BASIC
REPEAT
PRINT "SPAM"
UNTIL FALSE
[edit] bc
while (1) "SPAM
"
[edit] Befunge
Because the 2-D code space is toroidal, all loops are infinite unless explicitly stopped with @.
55+"MAPS",,,,,
[edit] Brainf***
++++++++++[->++++++>++++++++>+<<<]>+++++>
[+++.---.<.>---.+++>.<]
[edit] Brat
loop { p "SPAM" }
[edit] C
while(1) puts("SPAM");
or
for(;;) puts("SPAM");
or
do { puts("SPAM"); } while(1);
or
while(puts("SPAM"));
[edit] C++
while (true)
std::cout << "SPAM" << std::endl;
or
for (;;)
std::cout << "SPAM" << std::endl;
or
do
std::cout << "SPAM" << std::endl;
while (true);
[edit] C#
while (true)
{
Console.WriteLine("SPAM");
}
[edit] ColdFusion
This will result in a JRun Servlet Error and heap dump.
With tags:
<cfloop condition = "true NEQ false">
SPAM
</cfloop>
With script:
<cfscript>
while( true != false )
{
writeOutput( "SPAM" );
}
</cfscript>
[edit] Clojure
(loop [] (println "SPAM") (recur))
[edit] CoffeeScript
loop
console.log 'SPAM'
[edit] Common Lisp
(loop (write-line "SPAM"))
[edit] D
Some common ways to create an infinite printing loop:
import std.stdio;
void main() {
while (true)
writeln("SPAM");
}
import std.stdio;
void main() {
do
writeln("SPAM");
while (true);
}
import std.stdio;
void main() {
for ( ; ; )
writeln("SPAM");
}
import std.stdio;
void main() {
LOOP:
writeln("SPAM");
goto LOOP;
}
[edit] dc
[[SPAM
]P dx]dx
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.
[edit] Déjà Vu
while True:
print "SPAM"
Infinite recursion thanks to tail calls:
labda:
print "SPAM"
recurse
call
[edit] Delphi
while True do Writeln('SPAM');
[edit] DWScript
while True do
PrintLn('SPAM');
[edit] 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.
[edit] Ela
[edit] Direct Approach
open console
loop () = writen "SPAM" $ loop!
[edit] Non-strict version
open console list
loop () = writen "SPAM" :: (& loop!)
take 10 <| loop! //prints SPAM only first 10 times
[edit] Erlang
-module (main).
-export ([main/1]).
main(Any) ->
io:fwrite("SPAM~n",[]),
main(Any)
[edit] Euphoria
while 1 do
puts(1, "SPAM\n")
end while
[edit] F#
// Imperative Solution
while true do
printfn "SPAM"
// Functional solution
let rec forever () : unit =
printfn "SPAM"
forever ()
[edit] Factor
: spam ( -- ) "SPAM" print spam ;
: spam ( -- ) [ "SPAM" print t ] loop ;
[edit] FALSE
[1]["SPAM
"]#
[edit] Fantom
class Main
{
public static Void main ()
{
while (true)
{
echo ("SPAM")
}
}
}
[edit] Forth
: email begin ." SPAM" cr again ;
[edit] 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
DO
WRITE(*,*) "SPAM"
END DO
Although deprecated GOTO is still available
10 WRITE(*,*) "SPAM"
GOTO 10
[edit] GML
while(1)
show_message("SPAM")
[edit] Go
package main
import "fmt"
func main() {
for {
fmt.Printf("SPAM\n")
}
}
[edit] Groovy
while (true) {
println 'SPAM'
}
[edit] Haskell
forever (putStrLn "SPAM")
or
import Control.Monad.Fix (fix)
fix (putStrLn "SPAM" >>)
[edit] HicEst
DO i = 1, 1E20 ! for i with 16 or more digits: i == i + 1 == loop infinite
WRITE() "SPAM"
ENDDO
[edit] Icon and Unicon
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
[edit] IDL
while 1 do print,'SPAM'
[edit] 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)
[edit] Io
loop("SPAM" println)
[edit] J
(-[smoutput bind 'SPAM')^:_(1)
Alternatively,
smoutput bind 'SPAM'^:1e99 ''
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.
[edit] Java
while(true){
System.out.println("SPAM");
}
for(;;){
System.out.println("SPAM");
}
[edit] JavaScript
for (;;) print("SPAM");
while (true) print("SPAM");
[edit] Joy
DEFINE loop == [true []] dip while.
["SPAM\n" putchars] loop.
[edit] K
while[1; `0:"SPAM\n"]
[edit] 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.
[edit] Lang5
do "SPAM\n" . loop
[edit] Liberty BASIC
<CTRL><Break> is used to terminate such loops.
while 1
print "SPAM"
wend
end
[edit] Lisaac
{ "SPAM\n".print; }.endless_loop;
[edit] Logo
forever [print "SPAM]
[edit] Lua
while true do
print("SPAM")
end
--Another solution
repeat
print("SPAM")
until false
[edit] M4
define(`spam',`SPAM
spam')
spam
[edit] Make
spam:
@echo SPAM
$(MAKE)
[edit] Maple
> do print(SPAM) end;
[edit] Mathematica
While[True,
Print@"SPAM";
]
[edit] MATLAB / Octave
while (1), printf('SPAM\n'); end;
[edit] Maxima
do(disp("SPAM"));
[edit] MAXScript
while true do print "SPAM\n"
[edit] Metafont
forever: message "SPAM"; endfor end
[edit] Modula-2
LOOP
InOut.WriteString ("SPAM");
InOut.WriteLn
END;
[edit] Modula-3
LOOP
IO.Put("SPAM\n");
END;
[edit] MOO
while (1)
player:tell("SPAM");
endwhile
[edit] MUMPS
FOR WRITE "SPAM",!
[edit] Nemerle
while (true) WriteLine("SPAM");
Or, using recursion:
def loop() : void
{
WriteLine("SPAM");
loop();
}
[edit] NetRexx
/* NetRexx */
options replace format comments java crossref savelog symbols nobinary
say
say 'Loops/Infinite'
loop label spam forever
say 'SPAM'
end spam
[edit] Objeck
while(true) {
"SPAM"->PrintLine();
};
[edit] OCaml
while true do
print_endline "SPAM"
done
or
let rec inf_loop() =
print_endline "SPAM";
inf_loop()
in
inf_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.
[edit] Occam
#USE "course.lib"
PROC main (CHAN BYTE screen!)
WHILE TRUE
out.string("SPAM*c*n", 0, screen)
:
[edit] Octave
while(1)
disp("SPAM")
endwhile
[edit] Oz
for do
{Show 'SPAM'}
end
[edit] PARI/GP
while(1,
print("SPAM")
);
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:
until(print('SPAM),)
[edit] Pascal
while true do
writeln('SPAM');
Alternatively:
repeat
writeln('SPAM')
until false;
[edit] Perl
print "SPAM\n" while 1;
[edit] Perl 6
loop {
say 'SPAM';
}
In addition, there are various ways of writing lazy, infinite lists in Perl 6:
print "SPAM\n" xx *; # repetition operator
print "SPAM\n", ~* ... *; # sequence operator
map {say "SPAM"}, ^Inf; # upto operator
[edit] PHP
while(1)
echo "SPAM\n";
[edit] PicoLisp
(loop (prinl "SPAM"))
[edit] Pike
int main(){
while(1) write("SPAM\n");
}
[edit] PL/I
do forever;
put list ('SPAM'); put skip;
end;
[edit] Pop11
while true do
printf('SPAM', '%p\n');
endwhile;
[edit] PostScript
{}loop
[edit] PowerShell
for () {
"SPAM"
}
[edit] Prolog
repeat, write('SPAM'), nl, fail.
[edit] PureBasic
[edit] Repeat/Forever
Repeat
PrintN("SPAM")
ForEver
[edit] Goto
PrintIt:
PrintN("SPAM")
Goto PrintIt
[edit] Python
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 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.
[edit] 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")
[edit] Racket
#lang racket
;; Using recursion
(define (loop)
(displayln "SPAM")
(loop))
(loop)
;; Using a for loop
(for ([i (in-naturals)])
(displayln "SPAM"))
[edit] REBOL
forever [print "SPAM"]
[edit] Retro
[ "SPAM\n" puts -1 ] while
[edit] REXX
/*REXX program to display the word SPAM forever. */
do forever
say "SPAM"
end
[edit] Ruby
loop do
puts "SPAM"
end
[edit] Run BASIC
[loop] print "Spam" :goto [loop]
while 1
print "Spam"
wend
[edit] Salmon
while (true)
"SPAM"!;
[edit] Sather
class MAIN is
main is
loop
#OUT + "Spam\n";
end;
end;
end;
[edit] Scala
while (true)
println("SPAM")
[edit] 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))
[edit] sed
:loop
s/.*/SPAM/
p
t loop
Sed requires at least one line of input to execute, so run as follows:
echo | sed ':loop;s/.*/SPAM/;p;t loop'
[edit] Seed7
$ include "seed7_05.s7i";
const proc: main is func
begin
while TRUE do
writeln("SPAM");
end while;
end func;
[edit] Slate
[inform: 'SPAM'] loop
[edit] Smalltalk
[ true ] whileTrue: [ 'SPAM' displayNl ]
[edit] SNOBOL4
loop output = "SPAM" :(loop)
end
[edit] SNUSP
@\>@\>@\>@\>++++++++++===!/ < < < < \
| | | \M=@@@@+@+++++# \.>.>.>.>./
| | \A=@@+@@@@+++#
| \P=@@+@@+@@+++#
\S=@@+@+@@@+++#
[edit] 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.
[edit] SystemVerilog
program main;
initial forever $display("SPAM");
endprogram
[edit] Transact-SQL
WHILE 1=1 BEGIN
PRINT "SPAM"
END
[edit] Tcl
while true {
puts SPAM
}
# or
for {} 1 {} {
puts SPAM
}
[edit] 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
[edit] TI-89 BASIC
Loop
Disp "SPAM"
EndLoop
[edit] TorqueScript
While(1)
echo("SPAM");
[edit] Trith
["SPAM" print] loop
[edit] TUSCRIPT
TUSCRIPT has no infinite loop. 999999999 loops are the limit.
$$ MODE TUSCRIPT
LOOP/999999999
print "spam"
ENDLOOP
[edit] UNIX Shell
Use any of these loops:
while :; do echo SPAM; done
while true; do echo "SPAM"; done
until false; do echo "SPAM"; done
for ((;;)); do echo "SPAM"; done
[edit] C Shell
while (1)
echo SPAM
end
[edit] es
forever {echo SPAM}
[edit] UnixPipes
yes SPAM
[edit] Unlambda
``ci``s``s`kr``s``s``s``s`k.S`k.P`k.A`k.Mii
[edit] V
true [
'SPAM' puts
] while
[edit] Vala
for(;;) stdout.printf("SPAM\n");
while(true) stdout.printf("SPAM\n");
do stdout.printf("SPAM\n"); while(true);
[edit] 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")
}
[edit] Visual Basic
Do
Debug.Print("SPAM")
Loop
[edit] Visual Basic .NET
Platform: .NET
Do
Console.WriteLine("SPAM")
Loop
[edit] X86 Assembly
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
[edit] XPL0
code Text=12;
loop Text(0, "SPAM
")
[edit] Z80 Assembly
Using the Amstrad CPC firmware:
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"
- Programming Tasks
- Iteration
- 4DOS Batch
- 6502 Assembly
- 6800 Assembly
- ACL2
- ActionScript
- Ada
- Aime
- ALGOL 68
- AmigaE
- AppleScript
- AutoHotkey
- AWK
- BASIC
- Batch File
- BBC BASIC
- Bc
- Befunge
- Brainf***
- Brat
- C
- C++
- C sharp
- ColdFusion
- Clojure
- CoffeeScript
- Common Lisp
- D
- Dc
- Déjà Vu
- Delphi
- DWScript
- E
- Ela
- Erlang
- Euphoria
- F Sharp
- Factor
- FALSE
- Fantom
- Forth
- Fortran
- GML
- Go
- Groovy
- Haskell
- HicEst
- Icon
- Unicon
- IDL
- INTERCAL
- Io
- J
- Java
- JavaScript
- Joy
- K
- LabVIEW
- Lang5
- Liberty BASIC
- Lisaac
- Logo
- Lua
- M4
- Make
- Maple
- Mathematica
- MATLAB
- Octave
- Maxima
- MAXScript
- Metafont
- Modula-2
- Modula-3
- MOO
- MUMPS
- Nemerle
- NetRexx
- Objeck
- OCaml
- Occam
- Oz
- PARI/GP
- Pascal
- Perl
- Perl 6
- PHP
- PicoLisp
- Pike
- PL/I
- Pop11
- PostScript
- PowerShell
- Prolog
- PureBasic
- Python
- R
- Racket
- REBOL
- Retro
- REXX
- Ruby
- Run BASIC
- Salmon
- Sather
- Scala
- Scheme
- Sed
- Seed7
- Slate
- Smalltalk
- SNOBOL4
- SNUSP
- Standard ML
- SystemVerilog
- Transact-SQL
- Tcl
- TI-83 BASIC
- TI-89 BASIC
- TorqueScript
- Trith
- TUSCRIPT
- UNIX Shell
- C Shell
- Es
- UnixPipes
- Unlambda
- V
- Vala
- Vedit macro language
- Visual Basic
- Visual Basic .NET
- X86 Assembly
- XPL0
- Z80 Assembly
- GUISS/Omit