Loops/Infinite

From Rosetta Code
< Loops(Redirected from Loop/Infinite)
Jump to: navigation, search
Task
Loops/Infinite
You are encouraged to solve this task according to the task description, using any language you may know.
Specifically print out "SPAM" followed by a newline in an infinite loop.

Contents

[edit] 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
 

[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

Works with: QuickBasic version 4.5

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
Works with: Applesoft BASIC
Works with: ZX Spectrum Basic
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

[edit] Applesoft BASIC

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

[edit] Batch File

Using goto:

@echo off
:loop
echo SPAM
goto loop

Another variant which uses Windows NT's for statement:

Works with: Windows NT version 4 or later
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] Bracmat

whl'out$SPAM

[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++

Translation of: 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] Chapel

while true do writeln("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] COBOL

       IDENTIFICATION DIVISION.
PROGRAM-ID. Spam.
 
PROCEDURE DIVISION.
PERFORM UNTIL 1 <> 1
DISPLAY "SPAM"
END-PERFORM
 
GOBACK
.

OpenCOBOL supports a FOREVER clause for PERFORM which will have the same effect.

[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/0]).
 
main() ->
io:fwrite( "SPAM~n" ),
main().
 

[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

FORTRAN 77

 
10 WRITE(*,*) 'SPAM'
GO TO 10
END
 

Fortran 90

 
program spam
implicit none
do
write(*,*) 'SPAM'
end do
end program spam
 

[edit] Frink

 
while true
println["SPAM"]
 

[edit] GAP

while true do
Print("SPAM\n");
od;

[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] jq

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

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

[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.
LabVIEW Loops Infinite.png

[edit] Lang5

do "SPAM\n" . loop

[edit] Lasso

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

[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]

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 / Wolfram Language

While[True,
Print@"SPAM";
]

[edit] MATLAB / Octave

while true
fprintf('SPAM\n')
end

[edit] Maxima

do(disp("SPAM"));

[edit] MAXScript

while true do print "SPAM\n"

[edit] Metafont

forever: message "SPAM"; endfor end

[edit] МК-61/52

1	2	3	4	С/П	БП	00

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

[edit] Modula-2

LOOP
InOut.WriteString ("SPAM");
InOut.WriteLn
END;

[edit] Modula-3

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

[edit] Monte

 
while (true):
traceln("SPAM")
 

[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] Nimrod

while true:
echo "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

Works with: Rakudo Star version 2010.08
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

[edit] 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. */

[edit] 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. */

[edit] 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. */

[edit] 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. */

[edit] Ruby

loop {puts "SPAM"}
 

[edit] Rust

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

[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] Sidef

{ say "SPAM!" } while(true);

[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] Sparkling

while true {
print("SPAM");
}

or

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

or

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

etc.

[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] Swift

while true {
println("SPAM")
}

[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

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

[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

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

[edit] Wart

repeat :forever
prn "spam"

[edit] X86 Assembly

Works with: NASM version Linux
 
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"

[edit] zkl

while(1){println("SPAM")}
Personal tools
Namespaces

Variants
Actions
Community
Explore
Misc
Toolbox