Integer sequence: Difference between revisions

From Rosetta Code
Content deleted Content added
→‎{{header|Forth}}: add stack comment; don't print 0 at the end of the sequence
Added JavaScript
Line 1: Line 1:
{{task}}Create a program that, when run, would display all integers from 1 to ∞ (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.

An example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integers are represented as a 32-bit unsigned value with 0 as the smallest representable value, the largest representable value would be 4,294,967,295. Some languages support arbitrarily-large numbers as a built-in feature, while others make use of a module or library.

If appropriate, provide an example which reflect the language implementation's common built-in limits as well as an example which supports arbitrarily large numbers, and describe the nature of such limitations—or lack thereof.

=={{header|Ada}}==
<lang Ada>with Ada.Text_IO;
procedure Integers is
Value : Integer := 1;
begin
loop
Ada.Text_IO.Put_Line (Integer'Image (Value));
Value := Value + 1;
end loop;
end Integers;</lang>
alternative (iterating through all values of Positive (positive part of Integer) without endless loop):
<lang Ada>with Ada.Text_IO;
procedure Positives is
begin
for Value in Positive'Range loop
Ada.Text_IO.Put_Line (Positive'Image (Value));
end loop;
end Positives;</lang>
=={{header|ALGOL 68}}==
{{works with|ALGOL 68|Revision 1 - no extensions to language used.}}
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny].}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
The upper limit of the loop variable ''i'' is ''max int'' currently ''+2147483647'' for [[ALGOL 68G]].
<lang algol68>main:
(
FOR i DO
printf(($g(0)","$,i))
OD
)</lang>
Partial output:
<pre>
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,...
</pre>
=={{header|AutoHotkey}}==
This uses traytip to show the results. A msgbox, tooltip, or fileappend could also be used.
<lang AutoHotkey>x=0
Loop
TrayTip, Count, % ++x</lang>

=={{header|AWK}}==
<lang awk>BEGIN {
for( i=0; i != i + 1; i++ )
print( i )
}</lang>

Awk uses floating-point numbers. This loop terminates when <code>i</code> becomes too large for integer precision. With IEEE doubles, this loop terminates when <code>i</code> reaches <code>2 ^ 53</code>.

=={{header|BASIC}}==
{{works with|ZX Spectrum Basic}}
<lang basic>10 LET A = 0
20 LET A = A + 1
30 PRINT A
40 GO TO 20</lang>
{{works with|QBasic}}
<lang qbasic>A = 0
DO: A = A + 1: PRINT A: LOOP 1</lang>

=={{header|Brainf***}}==
This program assumes the implementation prints out the integer equivalent of the cell value, as opposed to the character equivalent, and is thus implementation-dependent. In addition, since nearly all brainf*** implementations provide only a byte of memory space for each cell, and assuming the previous requirement is satisfied, only 1-255 will be displayed before overflow to 0 causes the loop to end.
<lang brainf***>+[.+]</lang>

=={{header|Brat}}==
<lang brat>i = 1

while {
p i
i = i + 1
}</lang>

=={{header|C}}==
Prints from 1 to max unsigned integer (usually 2**32 -1), then stops.
<lang c>#include <stdio.h>

int main()
{
unsigned int i = 0;
while (++i) printf("%u\n", i);

return 0;
}</lang>

==={{libheader|GMP}}===
This one never stops. It's not even likely that you'll run out of memory before you run out of patience. <lang c>#include <gmp.h>

int main()
{
mpz_t i;
mpz_init(i); /* zero now */

while (1) {
mpz_add_ui(i, i, 1); /* i = i + 1 */
gmp_printf("%Zd\n", i);
}

return 0;
}</lang>

==={{libheader|OpenSSL}}===
OpenSSL provides arbitrarily large integers.

<lang c>#include <openssl/bn.h> /* BN_*() */
#include <openssl/err.h> /* ERR_*() */
#include <stdio.h> /* fprintf(), puts() */

void
fail(const char *message)
{
unsigned long code;

fprintf(stderr, "%s: error\n", message);
while (code = ERR_get_error())
fprintf(stderr, " %s\n", ERR_error_string(code, NULL));
exit(1);
}

int
main()
{
BIGNUM i;
char *s;

BN_init(&i);
for (;;) {
if (BN_add_word(&i, 1) == 0)
fail("BN_add_word");
s = BN_bn2dec(&i);
if (s == NULL)
fail("BN_bn2dec");
puts(s);
OPENSSL_free(s);
}
/* NOTREACHED */
}</lang>

=={{header|C sharp|C#}}==
<lang csharp>using System;
using System.Numerics;

class Program
{
static void Main()
{
BigInteger i = 1;
while (true)
{
Console.WriteLine(i++);
}
}
}</lang>
=={{header|C++}}==
<lang cpp>#include <iostream>
#include <cstdint>

int main()
{
uint32_t i = 0;
while(true)
std::cout << ++i << std::endl;

return 0;
}</lang>

=={{header|Clojure}}==
<lang Clojure>(map println (next (range)))</lang>

=={{header|Common Lisp}}==

<lang lisp>(loop for i from 1 do (print i))</lang>

=={{header|D}}==
<lang d>import std.stdio, std.bigint;

void main() {
BigInt i;
while (true)
writeln(++i);
}</lang>
Alternative:
<lang d>import std.stdio, std.traits, std.bigint, std.string;

void integerSequence(T)() if (isIntegral!T || is(T == BigInt)) {
T now = 1;
T max = 0;
static if (!is(T == BigInt))
max = T.max;

do
write(now, " ");
while (now++ != max);

writeln("\nDone!");
}

void main() {
writeln("How much time do you have?");
writeln(" 0. I'm in hurry.");
writeln(" 1. I've some time.");
writeln(" 2. I'm on vacation.");
writeln(" 3. I'm unemployed...");
writeln(" 4. I'm immortal!");
write("Enter 0-4 or nothing to quit: ");

string answer;
readf("%s\n", &answer);

switch (answer.toLower()) {
case "0": integerSequence!ubyte(); break;
case "1": integerSequence!short(); break;
case "2": integerSequence!uint(); break;
case "3": integerSequence!long(); break;
case "4": integerSequence!BigInt(); break;
default: writeln("\nBye bye!"); break;
}
}</lang>

=={{header|Delphi}}==
<lang Delphi>program IntegerSequence;

{$APPTYPE CONSOLE}

var
i: Integer;
begin
for i := 1 to High(i) do
WriteLn(i);
end.</lang>

=={{header|DWScript}}==
High(i) returns the maximum supported value, typically, it is the highest signed 64 bit integer.
<lang delphi>
var i: Integer;

for i:=1 to High(i) do
PrintLn(i);
</lang>

=={{header|E}}==

<lang e>for i in int > 0 { println(i) }</lang>

=={{header|Erlang}}==

<lang erlang> F = fun(FF, I) -> io:format("~p~n", [I]), FF(FF, I + 1) end, F(F,0). </lang>

=={{header|Euphoria}}==
<lang euphoria>integer i
i = 0
while 1 do
? i
i += 1
end while</lang>

=={{header|F_Sharp|F#}}==

<lang fsharp>// lazy sequence of integers starting with i
let rec integers i =
seq { yield i
yield! integers (i+1) }

Seq.iter (printfn "%d") (integers 1)</lang>

=={{header|Fantom}}==

<lang fantom>
class Main
{
public static Void main()
{
i := 1
while (true)
{
echo (i)
i += 1
}
}
}
</lang>

Fantom's integers are 64-bit signed, and so the numbers will return to 0 and continue again, if you wait long enough!

=={{header|Fish}}==
Since there aren't really libraries in Fish and I wouldn't know how to program arbitarily large integers, so here's an example that just goes on until the interpreter's number limit:
<lang Fish>0>:n1+v
^o" "<</lang>

=={{header|Forth}}==
<lang forth>: ints ( -- )
0 begin 1+ dup cr u. dup -1 = until drop ;</lang>

=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<lang fortran>program Intseq
implicit none
integer, parameter :: i64 = selected_int_kind(18)
integer(i64) :: n = 1
! n is declared as a 64 bit signed integer so the program will display up to
! 9223372036854775807 before overflowing to -9223372036854775808
do
print*, n
n = n + 1
end do
end program</lang>

=={{header|GAP}}==
<lang gap>InfiniteLoop := function()
local n;
n := 1;
while true do
Display(n);
n := n + 1;
od;
end;

# Prepare some coffee
InfiniteLoop();</lang>

=={{header|Go}}==
Size of int type is implementation dependent, but I think all implementations use 32 bits currently. After the maximum positive value, it rolls over to maximum negative, without error.
<lang go>package main

import "fmt"

func main() {
for i := 1;; i++ {
fmt.Println(i)
}
}</lang>
The big number type does not roll over and is limited only by available memory, or practically, by whatever external factor halts cpu execution: human operator, lightning storm, cpu fan failure, heat death of universe, etc.
<lang go>package main

import (
"big"
"fmt"
)

func main() {
one := big.NewInt(1)
for i := big.NewInt(1);; i.Add(i, one) {
fmt.Println(i)
}
}</lang>

=={{header|Haskell}}==
<lang haskell>mapM_ print [1..]</lang>

Or less imperatively:

<lang haskell>putStr $ unlines $ map show [1..]</lang>

=={{header|Icon}} and {{header|Unicon}}==
Icon and Unicon support large integers by default. The built-in generator seq(i,j) yields the infinite sequence i, i+j, i+2*j, etc. Converting the results to strings for display will likely eat your lunch before the sequence will take its toll.

<lang Icon>procedure main()
every write(seq(1)) # the most concise way
end</lang>

=={{header|J}}==
The following will count indefinitely but once the 32-bit (or 64-bit depending on J engine version) limit is reached, the results will be reported as floating point values.
<lang j> count=: (smoutput ] >:)^:_</lang>

The above works with both fixed sized integers and floating point numbers (fixed sized integers are automatically promoted to floating point, if they overflow), but also works with extended precision integers (which will not overflow, unless they get so large that they cannot be represented in memory, but that should exceed lifetime of the universe, let alone lifetime of the computer).

This adds support for extended precision (in that it converts non-extended precision arguments to extended precision arguments) and will display integers to ∞ (or at least until the machine is turned off or interrupted or crashes).
<lang j> count=: (smoutput ] >:)@x:^:_</lang>

=={{header|Java}}==
=={{header|Java}}==
Long limit:
Long limit:
Line 388: Line 15:
}</lang>
}</lang>


=={{header|K}}==
=={{header|JavaScript}}==
<lang k> {`0:"\n",$x+:1;x}/1</lang>
<lang javascript>var i = 0;

Using a <code>while</code> loop:

<lang k> i:0; while[1;`0:"\n",$i+:1]</lang>

=={{header|Liberty BASIC}}==
Liberty BASIC handles extremely large integers. The following code was halted by user at 10,000,000 in test run.
<lang lb> while 1
i=i+1
locate 1,1
print i
scan
wend
</lang>

=={{header|Lua}}==
<lang lua>
i = 1

-- in the event that the number inadvertently wraps around,
-- stop looping - this is unlikely with Lua's default underlying
-- number type (double), but on platform without double
-- the C type used for numbers can be changed
while i > 0 do
print( i )
i = i + 1
end
</lang>

=={{header|Mathematica}}==
Built in arbitrary precision support meanst the following will not overflow.
<lang Mathematica>
x = 1;
Monitor[While[True, x++], x]
</lang>

=={{header|ML/I}}==
<lang ML/I>MCSKIP "WITH" NL
"" Integer sequence
"" Will overflow when it reaches implementation-defined signed integer limit
MCSKIP MT,<>
MCINS %.
MCDEF DEMO WITHS NL AS <MCSET T1=1
%L1.%T1.
MCSET T1=T1+1
MCGO L1
>
DEMO</lang>

=={{header|OCaml}}==
with an imperative style:
<lang ocaml>let () =
let i = ref 0 in
while true do
print_int !i;
print_newline ();
incr i;
done</lang>

with a functional style:
<lang ocaml>let () =
let rec aux i =
print_int i;
print_newline ();
aux (succ i)
in
aux 0</lang>

=={{header|OpenEdge/Progress}}==
OpenEdge has three data types that can be used for this task:
<ol><li>INTEGER (32-bit signed integer)
<lang progress>DEF VAR ii AS INTEGER FORMAT "->>>>>>>>9" NO-UNDO.

DO WHILE TRUE:
ii = ii + 1.
DISPLAY ii.
END.</lang>
When an integer rolls over its maximum of 2147483647 error 15747 is raised (Value # too large to fit in INTEGER.).
</li>
<li>INT64 (64-bit signed integer)
<lang progress>DEF VAR ii AS INT64 FORMAT "->>>>>>>>>>>>>>>>>>9" NO-UNDO.

DO WHILE TRUE:
ii = ii + 1.
DISPLAY ii.
END.</lang>
When a 64-bit integer overflows no error is raised and the signed integer becomes negative.
</li>
<li>DECIMAL (50 digits)
<lang progress>DEF VAR de AS DECIMAL FORMAT "->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>9" NO-UNDO.

DO WHILE TRUE:
de = de + 1.
DISPLAY de.
END.</lang>
When a decimal requires mores than 50 digits error 536 is raised (Decimal number is too large.).
</li>
</ol>

=={{header|PARI/GP}}==
<lang parigp>n=0; while(1,print(++n))</lang>

=={{header|Perl}}==
<lang perl>my $i = 0;
print ++$i, "\n" while 1;</lang>

=={{header|Perl 6}}==
<lang perl6>.say for 1..*</lang>

=={{header|PicoLisp}}==
<lang PicoLisp>(for (I 1 T (inc I))
(printsp I) )</lang>

=={{header|PL/I}}==
<lang PL/I>
infinity: procedure options (main);
declare k fixed decimal (30);
put skip edit
((k do k = 1 to 999999999999999999999999999998))(f(31));
end infinity;
</lang>

=={{header|PostScript}}==
{{libheader|initlib}}
<lang postscript>
1 {succ dup =} loop
</lang>

=={{header|PureBasic}}==
<lang PureBasic>OpenConsole()
Repeat
a.q+1
PrintN(Str(a))
ForEver</lang>

=={{header|Python}}==
<lang python>i=1
while i:
print(i)
i += 1</lang>

Or, alternatively:
<lang python>from itertools import count

for i in count():
print(i)</lang>

Pythons integers are of arbitrary large precision and so programs would probably keep going until OS or hardware system failure.

=={{header|Retro}}==
Retro uses signed integer values.

<lang Retro>0 [ [ putn space ] sip 1+ dup 0 <> ] while drop</lang>

=={{header|Ruby}}==

<lang ruby>
i = 0
puts (i += 1) while true
</lang>

Ruby does not limit the size of numbers.

=={{header|Scala}}==
{{works with|Scala|2.8}}
<lang scala>def count(n:BigInt=0):Stream[BigInt]=n #:: count(n+1)
count() foreach println</lang>

=={{header|Scheme}}==

<lang scheme>
(let loop ((i 1))
(display i) (newline)
(loop (+ 1 i)))
</lang>

Scheme does not limit the size of numbers.

=={{header|Seed7}}==
Limit 2147483647:
<lang seed7>$ include "seed7_05.s7i";

const proc: main is func
local
var integer: number is 0;
begin
repeat
incr(number);
writeln(number);
until number = 2147483647;
end func;</lang>
"Forever":
<lang seed7>$ include "seed7_05.s7i";
include "bigint.s7i";

const proc: main is func
local
var bigInteger: number is 1_;
begin
repeat
writeln(number);
incr(number);
until FALSE;
end func;</lang>

=={{header|Tcl}}==
<lang tcl>package require Tcl 8.5
while true {puts [incr i]}</lang>
=={{header|TUSCRIPT}}==
<lang tuscript>
$$ MODE TUSCRIPT
LOOP n=0,999999999
n=n+1
ENDLOOP
</lang>

=={{header|Visual Basic .NET}}==
Visual Basic .NET supports an unsigned, 64 bit Integer (maxing out at a <i>whopping</i> 9 223 372 036 854 775 807), however, this is not an intrinsic type, it is a structure that is <i><b>not</b></i> supported by the CLS (Common Language Specification).

The CLS supported type (also a structure) is <i>Decimal</i> (an even more impressive range from positive 79 228 162 514 264 337 593 543 950 335 to negative 79 228 162 514 264 337 593 543 950 335), I have used a standard CLS <i>Integer</i> intrinsic type (from -2 147 483 648 through 2 147 483 647).

Note that attempting to store any value larger than the maximum value of any given type (say 2 147 483 648 for an Integer) will result in an OverflowException being thrown (<i>"Arithmetic operation resulted in an overflow."</i>)

<lang vbnet> For i As Integer = 0 To Integer.MaxValue
Console.WriteLine(i)
Next</lang>


while (true)
[[Category:Iteration]]
document.write(++i + ' ');</lang>

Revision as of 21:10, 26 August 2011

Java

Long limit: <lang java>public class Count{

   public static void main(String[] args){
       for(long i = 1; ;i++) System.out.println(i);
   }

}</lang> "Forever": <lang java>import java.math.BigInteger;

public class Count{

   public static void main(String[] args){
       for(BigInteger i = BigInteger.ONE; ;i = i.add(BigInteger.ONE)) System.out.println(i);
   }

}</lang>

JavaScript

<lang javascript>var i = 0;

while (true)

   document.write(++i + ' ');</lang>