# Print all integers

Write a program or function which will provably print all integers exactly once given infinite time and memory.

Possible outputs could be:

0, 1, -1, 2, -2, 3, -3, 4, -4, …

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -2, -3, -4, -5, -6, -7, -8, -9, 10, 11, …


This is not a valid output, as this would never enumerate negative numbers:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, …

• The output must be in decimal, unless your language does not support decimal integer (in that case use the natural representation of integers your language uses).

• Your program has to work up to the numbers with the biggest magnitude of the standard integer type of your language.

• Each integer must be separated from the next using any separator (a space, a comma, a linebreak, etc.) that is not a digit nor the negative sign of your language.

• The separator must not change at any point.

• The separator can consist of multiple characters, as long as none of them is a digit nor the negative sign (e.g. ,  is as valid as just ,).

• Any supported integer must eventually be printed after a finite amount of time.

### Scoring

This is , so the shortest answer in bytes wins

var QUESTION_ID=93441,OVERRIDE_USER=41723;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>

• If our language supports infinite lists, can we output the list from a function rather than printing? (Calling print on such a list would print its elements one at a time forever.)
– xnor
Sep 16, 2016 at 8:57
• I feel like the requirement on arbitrary-size integers does nothing but discourage languages without such integers from participating. They either have to have an import they can use or solve a totally different challenge from everyone else.
– xnor
Sep 16, 2016 at 9:10
• @xnor Changed, though that kinds of ruins the very name of the challenge. Sep 16, 2016 at 9:14
• @xnor, languages with arbitrary precision integers still have to solve a different problem from everyone else, so all that that change has accomplished is to make this problem boringly trivial in a lot of languages. Sep 16, 2016 at 9:54
• @PeterTaylor Yeah, this is unfortunate. The wrapping solutions don't feel to me like they are printing any negatives, but I don't see a way to firmly specify the difference when it's a matter of representation.
– xnor
Sep 16, 2016 at 9:58

# Reticular, 12 bytes

0dp1+dpd0#2j


Try it online!

## Explanation

0dp1+dpd0#2j   ; stack
0              ; [0]
dp            ; [0]   PRINTED 0
1+          ; [1]
dp        ; [1]   PRINTED 1
d0#     ; [1, -1]
2j   ; skip two spaces after the j, wrapping to..
p            ; [1]   PRINTED -1
1+          ; [2]
dp        ; [2]   PRINTED 2
d0#     ; [2]   PRINTED -2
; etc.


## Pyth , 7 bytes

0.V1_bb

Explanation

0       # print 0
.V1    # increment 'b' forever, starting on 1
_b  # print -b
b # print b


## MATLAB 65 bytes

My earlier post was faulty because the loop does not stop. A better try is this:

a=intmin('int64');(a:-a)'


but while this will work for the smaller int8 type it will not for int64 as the maximum array size will (of course) be exceeded. Note that transposing the vector prevents the console output from being interrupted by 'columns m to n' messages.

Another funny with MATLAB is that integers do NOT roll over, thus intmax('int64') + 1 == intmax('int64') not intmin('int64') as I expected. Also, MATLAB does not have a 'do' loop, So the best I can think of is this:

a=intmin('int64');b=-a;while(1) a, if a==b break, end; a=a+1; end


an then only if we allow the 'any separator' to allow this:

a =
-9223372036854775808
a =
-9223372036854775807
...
a =
9223372036854775806
a =
9223372036854775807


There must be a better way!

# Perl 6, 22 bytes

loop {say $--;say ++$}


## Explanation:

loop {
say   (state $= 0)--; # prints ｢0␤｣ first time around, then ｢-1␤｣ ｢-2␤｣ etc say ++(state$ = 0)    # prints ｢1␤｣ first time around, then ｢2␤｣ ｢3␤｣ etc
}


# C, 51 50 bytes

void f(){long i=0;for(;;)printf("%d %d ",i++,-i);}


I could save a byte by doing int instead of long, but since this can go longer than int without wrapping I'm leaving it.

Output:

0 -1 1 -2 2 -3 3 -4 4 -5 5 -6 6 ...

• This program will run forever, shouldn't it terminate after printing all the "longs"? P.S. you can save a byte using for(;;) in place of while(1) Sep 16, 2016 at 17:30
• A lot of the other answers here run forever, so I just went with it. That way, you can #define long into arbitrarily large types. Good tip on saving a byte though.
– Cody
Sep 16, 2016 at 18:07
• It's pointless to use long with a %d conversion (instead of %ld). On x86-64 with 64-bit long, printf it will only look at the low 32 bits of its args. I can't think of a plausible way for any normal calling convention on any ISA where %d would print a number outside the range of int; most calling conventions require functions to ignore garbage in high bits. You could save a ; by putting the variable declaration inside the for(). i.e. for(int i=0;;)printf.... Especially since you didn't omit the return-type or anything, so this is valid C99. Sep 16, 2017 at 7:35
• By the way, you can save 5 bytes by removing void . The function will be declared as int, which will give a warning, but this is code golf, not following best practices. May 6, 2020 at 14:56
• You can place the i inside () so you don't need a type specifier. f(i){i=0;for(;;)printf("%d %d ",-i,i++);}main(){f();} (P.S: This uses UB for the i++ part. So you may have to move the i++ to a different i.) Jul 18, 2023 at 13:34

# bash, 46 Bytes

echo 0;for((i=1;;i++)){ echo -e "$i\n-$i"; }

• You don't need a space after ;, or after {. Sep 16, 2017 at 7:37
• @PeterCordes Unfortunately, I get bash: syntax error near unexpected token ˋ{echo' if I remove the space after {. Mar 14 at 21:10
• @KaiBurghardt: You're right, in this context we do need the space after {. Only the space after the ; can be removed here, in Bash 4.3 or 5.2 that I tested. I was probably thinking of function definitions and other uses of braces where {command} is valid. Mar 14 at 21:18

# dc, 16 bytes

zpc[zp0r-prdx]dx


Explanation:

zp    # Push stack depth (0) and peek (print top of stack and newline without popping)
c     # Clear stack
[     # Open macro definition
z    #  Push stack depth (1 on first iteration, because this macro is on the stack)
p    #  Peek (print positive number)
0r-  #  Subtract ToS from 0 (make negative)
p    #  Peek (print negative number)
rdx  #  Rotate (move this macro on top of the negative number), duplicate, and execute
]dx   # Duplicate string and execute as macro


This does feel a little too similar to yeti's answer; however, this solution makes use of all-natural, grass-fed, free-range negative numbers!

In case anyone finds these to be of interest, here are some other approaches I tried:

zp[zp_1/plax]dsax    # uses a named macro rather than a stack-squatting macro
zpc[zdp;ar-prdx]dx   # uses an array to fetch a 0 for subtracting from...in retrospect this
#  is just a longer way of writing 0' and has no advantages whatsoever

0p[z1-p_1~+prdx]dx   # uses ~ with -1 to convert a positive to a negative
0p[zp_1~+plax]dsax   # uses ~ with _1 in a named macro
#  The difference between the two above is in stack depth: Since the
#  named macro doesn't reside perpetually on the stack, we don't lose
#  access to a number through z'. Because the first macro must stay on
#  the stack, we have to decrement (1-') to start with 1 and -1. (Both
#  methods require explicitly printing 0 so that it's only printed once.)

0p[zp0r-pzz>a]dsax   # uses an always-true conditional, which is also kind of pointless
0p[zp_1*ddp=a]dsax   # _1*' == 0r-';  ddp=a' == pzz>a'; just some alternative notations
z[p1+_1/p_1/lax]dsax # I don't remember what I was doing with these last two
[zpd_1/+z-p0d=a]dsax #


Even though these other methods are all longer, I think at least half the fun is in discovering new mechanisms that one could adapt for use in other situations.

• "In case anyone finds these to be of interest" ... I do! ;-)
– user19214
Sep 17, 2016 at 6:34

# Haxe, 46 bytes

function f(){var i=0;while(0<1)trace(i++,-i);}


## Racket 56 bytes

(saved 12 bytes with suggestion by @StevenH)

(λ()(let l((i 0))(printf"~a, ~a, "i(- -1 i))(l(+ 1 i))))


Ungolfed:

(define(f)
(let loop ((i 0))
(printf "~a, ~a, "  i  (- -1 i))


Following can also be used:

(for((i(in-naturals)))(printf"~a, ~a, "i(- -1 i)))


or:

(for ((i (in-naturals)))
(printf "~a, ~a, " i (- -1 i)))


Testing:

(f)

0, -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, -14, 14, -15, 15, -16, 16, -17, 17, -18, 18, -19, 19, -20, 20, -21, 21, -22, 22, -23, 23

• You can avoid the first printf entirely by replacing (* i -1) with (- -1 i). Oct 7, 2016 at 6:17
• Thanks for the suggestion. I have added it to my answer.
– rnso
Oct 7, 2016 at 6:29

# RProgN, 22 21 Bytes

►0p11¿]p]0\-p1+]}


Note the trailing space IS required.

Saved a byte by replacing the -1 * n with a simple 0 - n, because defining -1 in ► form takes too many bytes.

## Explination

►           # Read this word as a single-character based command.
0p          # Print the number 0
11          # Push two 1's to the stack.
¿           # While the top of the stack is truthy, pop the top of the stack.
]       # Clone the top of the stack, containing i.
p       # Print it.
]       # Clone it again.
0 \ - * # Push 0 to the stack, swap the 0 and the object underneith it, giving 0, n instead of n, 0. Subtract giving -n.
p       # Print it.
1+      # Add one to i
]       # Clone it for the next truthy check
}           # End the while statement
# Required to interpret the while loop correctly.


## Output

0
1
-1
2
-2
3
-3
4
-4
5
...


This language looks nothing like it's former self. ;(

# ForceLang, 8767 59 bytes

def w io.writeln
w 0
label a
w set i 1+i
w i.mult -1
goto a


# C, 44 bytes

long l;f(){printf("%ld ",l);l=(l<=0)-l;f();}


Note that the (implicit) int return type does not cause f to require a return because f never reaches the end of the function.

This code uses the fact that globally defined variables are initialized to zero.

Note that on a system with unlimited memory (or with a compiler that does tail recursion elimination)there will be no stack overflow, therefore this program fulfils the requirements.

C++, 84 Bytes

#include <iostream>
int main(){for(int i=0;;)std::cout<<i++<<','<<-i<<',';return 0;}


Edit: thanks for the debugging, commenters

• Welcome to PPCG! All answers need to be full programs or functions and the relevant includes/namespaces need to be counted as well. If you make your submission a full program, it should compile in any existing compiler as is, and if it's a function it should be possible to drop it into any program and use and compile it without any other additional code. Sep 17, 2016 at 15:53
• That loop doesn't print a delimiter between the numbers. Oct 13, 2016 at 23:08
• C++ implicitly returns 0 from main, so you can ditch the whole return 0; for -9 bytes, also the space in #include <iostream> is not required
– c--
Jun 28, 2022 at 15:48

# MATL, 9 bytes

0t_DQtDT


You can Try it online! (and let's hope that the process on the server actually terminates once you close your browser...)

Explanation:

0             % Push 0 on stack
       T    % Start infinite loop
t_D         % Duplicate top element, negate and display (which consumes the duplicate)
QtD      % Add 1 to top of stack, duplicate and display (which consumes the duplicate)


# Brain-Flak, 28 + 3 = 31 bytes

To get a program that outputs every integer in some finite time (but the whole thing in infinite time) you need to use debug flags.

Try it online

(@dv()@dv){([[{}]@dv]()@dv)}


The program is 28 bytes and the command line flag is 3 making the total 31.

An alternative that does not technically fit the specs:

Try it online

(({})()){([([({})])]())}


If you run the program you will notice there is no output. This is because Brain-flak programs output when they terminate. It will output all the numbers at once once infinite time has elapsed. If you want to verify that it works try it online with debug flags.

# Java 8, 87 bytes

Alternative solution using an IntStream to iterate through all integers.

java.util.stream.IntStream.rangeClosed(1<<31,~1<<31).forEach(n->System.out.println(n));


## Alternative, 57 bytes

I didn't want to post this as my main answer, because it's just stolen from @KevinCruijssen's Java 7 answer, switched to go from negative to positive for no particular reason, and turned into a lambda. But it is technically shorter.

()->for(int i=1<<31;i<0;System.out.println(i+"\n"+~i++));


# JS (NON - ES6), 25 bytes

for(n=0;;)alert([~n,n++])


Uses binary NOT (~) for reverse sign and deincrement.

# Excel VBA, 25 20 Bytes

Anonymous VBE immediate window function that takes no input and outputs to the vbe immediate window

Do:?1-n;n:n=n+1:Loop


Note: Excel will appear to be non-responsive after executing to n=6012, adding a DoEvents: call at the beginning of any of the lines in the do...loop corrects this visual bug, but is not necessary for correct execution.

# Aceto, 9 bytes

dpnd~pnIO

d duplicates the top val
p prints it
n does a newline
~ negates  the top val
I Increments the top val
O returns to the beginning of the program

Try it online!

# Common Lisp, 42 bytes

(do((i 0))(())(print(- i))(print(incf i)))


Try it online!

# Implicit, 65 4 bytes on TIO

(%.ß


Requires that the input box on TIO be empty.

(...    « do..while top of stack truthy                 »;
%      «  print top of stack as int                    »;
.     «  increment (reads from input if stack empty)  »;
ß    «  print space                                  »;
¶   « (implicit) just kidding, loop forever         »;


Try it online!

# Implicit, 5 bytes

0(%.ß
0        « push 0           »;
(%.ß    « (same as above)  »;

• But how does this eventually print the negative numbers?
– user85052
Dec 14, 2019 at 6:48

# Momema, 26 bytes

z0-8*0-9 00+1*0-8-*0-9 0z1


Try it online!

This outputs null bytes as the separator (though TIO displays them as spaces).

Alternatively, at a cost of 1 byte, here's a version that uses tabs instead of null bytes:

z0-8*0-9 9 0+1*0-8-*0-9 9z1


## Explanation

                                                   #  a = 0
z   0     #  label z0: jump past label z0 (no-op)  #  while true {
-8  *0    #            output number [0]           #    print a
-9  0     #            output chr 0                #    print '\0'
0   +1*0  #            [0] = [0] + 1               #    a++
-8  -*0   #            output number -[0]          #    print -a
-9  0     #            output chr 0                #    print '\0'
z   1     #  label z1: jump past label z1          #  }


# Forked, 21 bytes

%A!v
>1+%A!AF*!%A!


First, this does %A! (print 0 followed by a newline), then executes the code in my original answer below, before I realized we were supposed to print 0 too:

# Forked, 12 bytes

1+%A!AF*!%A!


Try it online!

• 1+ - add 1 to the top of the stack
• % - print top of stack as integer
• A! - print 0xA (ASCII newline)
• AF*! - print 0xA × 0xF = 0x2D (ASCII -)
• % - print top of stack as integer
• A! - print 0xA (ASCII newline)

Forked is two-dimensional, so the IP wraps upon hitting the edge of the playing field.

This just loops through every integer, prints it followed by a newline, then prints it again, preceded by a - and proceeded by a newline.

# Appleseed, 41 bytes

(def I(q(((n 0))(cons n(I(sub(less? n 1)n


Defines a function I that takes no arguments and returns an infinite list of integers, starting (0 1 -1 2 -2 ...). Try it online!

Note: Appleseed is in the early stages of development at the moment, so if this code stops working at some point in the future, ping me and I'll update it.

### Ungolfed + explanation

; Load the library for functions & macros such as lambda
; Define all-integers to be...
(def all-integers
; a lambda function with one optional argument, n, whose default value is 0
(lambda ((n 0))
; The function prepends n to...
(cons n
; the result of a recursive call...
(all-integers
; whose argument is (n<1) - n, i.e. -n if n is positive, else -n+1
(sub (less? n 1) n)))))


# Pyt, 11 bytes

00Ƥ⁺ĐĐ~ƤƤł


Try it online!

00   pushes 0 twice
Ƥ    prints with a newline separator
indicator for looping
⁺    increments
ĐĐ   duplicates twice
~    negates top value
ƤƤ   prints positive and negative value
ł    loops till top is zero (never)


# Coconut, 25 bytes

def f(n=0)=[n,~n]::f(n+1)


Try it online!

# Milky Way, 9 bytes

&{!k1-!j}


Try it online!

## How?

           initial Stack: ["", 0]
&{      }  infinite loop
!        output ToS
k       negative absolute value
1-     subtract 1
!    output ToS
j   absolute value


# Yabasic, 22 bytes

An anonymous answer that takes no input and outputs all integers to the console.

?0
Do
i=i+1
?-i,i
Loop


Try it online!

# QBasic, 23 bytes

Script that takes no input and outputs to the console. Values are newline delimited and increment in the order of $0, -1, 1, -2, 2, \cdots$.

?0
Do
i=i+1
?-i
?i
Loop


## Python 3, 44 bytes

i=0;print(i)
while 1:i+=1;print(i);print(-i)
`

Try it online!