title: Shortest auto-destructive loop

text:
# Question
Title: Shortest auto-destructive loop
Your task is to write a full program or function that takes no input and runs any type of loop (`while`, `for`, `foreach`, `do`, `do-while`, `do-loop`, `goto`, recursion, etc) that will end in causing an error, which means that the program must stop itself running and exit.

**Rules:**

1. The error must be a run-time error, unhandled exception, or anything that makes the program end itself.
2. The error must produce the stop and exit from the program without calling explicitly `exit;` (or equivalent) at some point.
3. Messages like `Warning:`, `Notice:`, etc, that do not cause the program to end itself are not valid. For example in PHP divisions by zero produces a `Warning` message but the program will not stop and will still run, this is not a valid answer.
4. The loop must run at least one full cycle. In other words the error can happen starting at the second cycle and further. This is to avoid to cause the error using incorrect code syntax: the code must be syntactically correct.
5. The loop can be even infinite (example `for(;;);`) if it respects the above said rules, but must take no longer than 2 minutes to end itself in a run-time error.
6. Recursion without Tail Call Optimization is invalid (,).
7. This is so the shortest code wins.
8. Standard loopholes are forbidden.

**C# example (test online):**

```
using System;
public class Program {
    public static void Main() {
        int i;
        int[] n;
        n = new int[5];
        for(i=0; i<7; i++) {
            n[i] = i;
            Console.WriteLine(n[i]);
        }
    }
}

Output:

0
1
2
3
4
Run-time exception (line 9): Index was outside the bounds of the array.

Stack Trace:

[System.IndexOutOfRangeException: Index was outside the bounds of the array.]
  at Program.Main(): line 9

```

**Leaderboard:**

```
var QUESTION_ID=104323,OVERRIDE_USER=59718;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;font-family:Arial,Helvetica; font-size:12px}#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>
```

Thanks to Martin Ender for the Leaderboard Snippet

# Answer
# MATL, ~~5~~ 1 byte

*Idea taken from @MartinEnder's CJam answer*

```
`

```

Try it online!

```
`    % Do...while loop
     % Implicit end. The loop continues if the top of the stack is true.
     % After the first iteration, since the stack is empty, the program
     % implicitly tries to take some non-existing input, and finishes
     % with an error

```

---

### Old version

```
2:t"x

```

Try it online!

```
2:   % Push [1 2]
t    % Duplicate
"    % For each (i.e. do the following twice)
  x  %   Delete top of the stack. Works the first time. The second it tries to
     %   implicitly take some non-existing input, and finishes with an error

```
> 35 votes

# Answer
# Python, 16 bytes

The non-interesting 0 division approach:

```
for x in 1,0:x/x

```

The first iteration computes `1 / 1`, which works fine. The second iteration tries to compute `0 / 0`, resulting in a `ZeroDivisionError` being thrown.

## 17 bytes (personal favourite)

```
i=1
while i:del i

```

Initially, `i=1` which is truthy, so the loop is entered.

The first time the loop is run, the variable `i` is deleted.

This means that, the second time, `i` is no longer a variable and therefore its evaluation fails with `NameError: name 'i' is not defined.`

---

Another 15 byte solution would be `def _():_()` (newline) `_()`, because Python does not optimize tail recursion. However, this violates rule #6.
> 37 votes

# Answer
# Jelly, ~~3~~ 2 bytes

```
Ṿß

```

Kills itself by running out of memory. Locally does so after ~100 seconds.

Try it online! (death certificate in *Debug* drawer)

### How it works

```
Ṿß  Main link. Argument: x. Implicit first argument: 0

Ṿ   Uneval; yield a string representation of x.
 ß  Recursively call the main link.
    Jelly uses TCO, so the first cycle finishes successfully before entering
    the next one.

```

The first few iterations yield:

```
'0'
'”0'
'””,”0'
'””,””,”,,””,”0'
'””,””,”,,””,””,”,,””,”,,”,,””,””,”,,””,”0'
'””,””,”,,””,””,”,,””,”,,”,,””,””,”,,””,””,”,,””,”,,”,,””,””,”,,””,”,,”,,””,”,,”,,””,””,”,,””,””,”,,””,”,,”,,””,””,”,,””,”0'

```

After that, it gets real ugly, real fast.
> 19 votes

# Answer
# , 2 bytes

```
òl

```

Try it online!

This is the *perfect* challenge for V because I already do that all the time! In fact, V doesn't even have any conditionals, it only has functions that break on an error. In this case, the `ò` means "repeat forever" and the `l` means "move right".

In an empty buffer (no input) this will break on the first pass and produce no output. If there *is* input, it will break once we move post the last character of input, and output all of the input (making this also a cat program)
> 15 votes

# Answer
# JavaScript (ES6), 13 bytes

```
f=_=>f(_?a:1)

```

This is a recursive function that runs fine once, then throws `ReferenceError: a is not defined` and quits.

Here's a 15-byte non-ES6 version:

```
for(i=0;;)i=i.a

```

This runs fine once, then throws `TypeError: i is undefined` and quits.
> 11 votes

# Answer
# GNU sed, ~~15 13~~ 5 bytes

-2 Thanks to seshoumara
-8 Thanks to zeppelin

```
H;G;D

```
1. Appends a newline and the hold space to the pattern space.
2. Appends a newline and the pattern space to the hold space.
3. Deletes up to the first newline and starts over.

This quickly runs out of memory:

```
$ time (echo|sed 'H;G;D')
sed: couldn't re-allocate memory

real    0m1.580s
user    0m0.545s
sys     0m1.012s

```
> 11 votes

# Answer
# Bash 4.2, 22 bytes

```
exec $0 $@ $[2**$#%-1]

```

Doesn't work in TIO because it has Bash 4.3, and the bug I'm relying on was *finally* fixed.

### Verification

```
$ xxd -c 22 -g 22 self-destruct
0000000: 6578656320243020244020245b322a2a2423252d315d  exec $0 $@ $[2**$#%-1]
$ ./self-destruct
Floating point exception

```

This crashes once the program tries to compute **263 mod -1**, which crashes in Bash 4.2 and older versions due to a known bug.
> 10 votes

# Answer
# Befunge-93, 3 bytes (possibly 1 or 0)

```
!%!

```

Try it online!

On the first iteration of the loop, the stack is empty, which is the equivalent of all zeros. The `!` (not) operation thus converts the stack top to 1, and the `%` (modulo) operation calculates 0 mod 1, leaving 0. The next `!` operation converts that 0 to a 1 before the program counter wraps around and begins the loop again.

On the second iteration, the first `!` operations converts the 1 that is now at the top of the stack to a 0. The `%` operation then calculates 0 mod 0, which produces a division by zero error on the reference interpreter, and thus terminates the program.

There's also the more boring 1 byte answer, although I'm not sure if this is considered valid.

```
"

```

Try it online!

This `"` command starts a string, thus every space on the rest of the line is pushed onto the stack until the program counter wraps around and encounters the `"` again closing the string. It'll then need to wrap around a second time to repeat the process starting another string and pushing another 79 spaces onto the stack. Eventually this will either run out of memory (the reference interpreter behaviour) or produce a stack overflow.

Now if you want to really push the rules there's also technically a zero byte solution.

```

```

If you take this ruling to mean that *any* interpreter defines the language (as many here do), then we can assume for the moment that the Befunge language is defined by this interpreter. And one of the "features" of that interpreter is that it pushes an *Undefined* value onto the stack for each loop of the playfield when executing a blank program. Given enough time it will eventually run out of memory.

How fast that happens will depend on the speed of the computer, the available memory, and the browser being used. On my machine I found that Microsoft Edge worked best, but even then it was "only" using 500MB after two minutes. It wasn't until around the fifteen minute mark (with several gigabytes used) that Edge decided to kill the process and refresh the tab. So it's unlikely to make it under the two minute time limit, but with the right conditions that wouldn't necessarily be out of the question.
> 10 votes

# Answer
# PHP, ~~22~~ ~~21~~ ~~20~~ 18 bytes

This relies on PHP allowing one to give a function name to a variable and try to run it.

This simply concatenate the name of the `pi` function twice. This kills PHP with a `Fatal Error: Uncaught Error: Call to undefined function pipi() in [...][...]`.

```
while($x.=pi)$x();

```

This works similar to my old answer.

---

**Old answer, 20 bytes**

PHP allows you to increment characters, using the increment operator. It only works on the `a-z` range, but is enough.

```
for($x=pi;;)$x=$x();

```

I believe this fulfills all the required points and the loop does run once.

You can see if because you will get the error `Fatal error: Function name must be a string`.

---

How this works, step by step:

* Assign `pi` to `$x`.
Since `pi` is being used as a constant, PHP will check if exists.
Since it doesn't, PHP shows a warning saying `Use of undefined constant pi - assumed 'pi'` (Basically: since the constant doesn't exist, it is assumed to be a string)
* Loop the first time
    + Run the function `$x()`.
    Since `$x` has the value `pi`, it will run the function `pi()`.
* Store the value in `$x`.
`$x` now has π, instead of `pi`
* Loop for the second time
    + Run the function `$x()`.
    Since `$x` has π, it will run the function `3.14159...()`.
    + π isn't a string, killing the program at this point with a `Fatal Error`.

---

Thanks to @Titus for finding the `pi()` function, saving me **1** byte!
> 10 votes

# Answer
## C, 21 bytes

```
i;f(){for(;1/!i++;);}

```

Here `i` is guaranteed to start off as `0`.

It can be confirmed that this runs once like so:

```
i;f(){for(;1/!i++;)puts("hi");}
main(){f();}

```

Which, on my machine, results in:

```
llama@llama:...code/c/ppcg104323loop$ ./a.out
hi
zsh: floating point exception (core dumped)  ./a.out

```

The shortest recursive solution I can find is **22 bytes**:

```
f(i){f(i-puts(""-i));}

```

`gcc` only does tail call elimination at `-O2` or higher, at which point we need to call a function like `puts` to prevent the entire thing from being optimized away. Confirmation that this works:

```
llama@llama:...code/c/ppcg104323loop$ cat loop.c
main(){f();}
f(i){f(i-puts(""-i));}
llama@llama:...code/c/ppcg104323loop$ gcc -O2 -S loop.c 2>/dev/null
llama@llama:...code/c/ppcg104323loop$ grep call loop.s
    call    puts
    call    f

```

The following is a full program, which assumes that it is called with no command line arguments, at **22 bytes**:

```
main(i){for(;1/i--;);}

```

which is equivalent to the function of the same length:

```
f(i){for(i=1;1/i--;);}

```
> 9 votes

# Answer
## R, 22 25 22 20 18 bytes

Edit: Thanks to @Mego for pointing out that R does not support tail call optimization.

Edit4: Found an even shorter solution which simple yet quite intricate.

```
repeat(ls(T<-T-1))

```

The answer uses the builtin boolean truthy variable, `T` which is decremented indefinitely in the repeating loop. The function `ls()` is called each iteration which lists all objects in the current environment. However, the first argument `name` specifies from which environment from which to list objects. From the R-documentation we find that:

> The name argument can specify the environment from which object names are taken in one of several forms: as an integer (the position in the `search` list); as the character string name of an element in the search list; or as an explicit `environment` (including using `sys.frame` to access the currently active function calls).

This principally means that in the first iteration we run `ls(-1)` which would return `character(0)` (standard when trying to access the non-existent `everything-except-the-first` element of any character type object). During the second iteration, `T` is decremented by two and we subsequently call `ls(-3)` which in turn returns the error:

```
Error in as.environment(pos) : invalid 'pos' argument

```

This is because we try to list `everything-except-the-third` element but the local environment only contains the variable `T` at this point (as such, `ls()` would return a list of length `1` at this iteration) and an error is returned.
> 9 votes

# Answer
# FALSE, 8 bytes

I really like this language.

```
1[$][.]#

```

This pushes a `1`, then `[$][.]#` loops while `$` is true (duplicate top of stack) and (`.`) outputs it. This interpreter crashes after the single `1` is printed (evidence of the loop running at least once.) It seems to be a bug in this interpreter. The following 9-byte program should work in all compliant interpreters:

```
1[$][..]#

```
> 8 votes

# Answer
# QBasic, 17 bytes

This code is very weird.

```
DO
i=11+a(i)
LOOP

```

### How it works

In QBasic, variables are preinitialized. A regular variable without any type suffix, like `i` here, is preinitialized to zero.

Except if you try to subscript into that variable like an array... in which case, it's an array of 11 zeros.\*

On the first time through the loop, therefore, `i` is `0` and `a` is an array. `a(i)` gives the zeroth element of the array (which is `0`). All well and good. We set `i` to `11` and loop. But now `11` is not a valid index for the array `a`, and the program halts with `Subscript out of range`.

A 19-byte version that better shows what's going on:

```
DO
?a(i)
i=i+1
LOOP

```

This will print `0` eleven times before erroring.

---

** Conceptually, it's a 10-element array. Most things in QBasic are 1-indexed, but arrays aren't, possibly for implementation reasons. To make things work as expected for programmers, QBasic throws in an extra entry so you can use indices 1 to 10. Index 0, however, is still perfectly accessible. Go figure.*
> 7 votes

# Answer
# **MATLAB, 18 bytes**

This can be run as a script:

```
for j=1:2;j(j);end

```

The first iteration is fine, since `j(1)` is just `1`. The second iteration crashes with an array out of bounds error, as `j(2)` exceeds the dimensions of `j`, which is a 1x1 array.

This also can be run as a script, but it only works the first time you run it. Still, it's a hilarious enough abuse of MATLAB's predefined constants that I thought I'd include it. It's also 18 bytes.

```
while i/i;i={};end

```

When run in a workspace that the variable `i` hasn't been defined in yet, this assumes `i` is the imaginary unit, so `i/i = 1`. In the first loop, the assignment `i={}` creates an empty cell array called `i`. On the second iteration, the loop exits with "Undefined operator '/' for input arguments of type 'cell'."
> 6 votes

# Answer
# Perl 6, 13 bytes

```
loop {5[$++]}

```

Indexes an integer literal in an infinite loop.
Relies on fact that on scalar values, the array indexing syntax can be used with index `0` (returning the value itself), but throws an `Index out of range` error for any other index.
> 6 votes

# Answer
## CJam, 4 bytes

```
1{}g

```

Try it online!

The first iteration of the empty `{}g` loop pops the `1`, which tells it to continue. The second iteration tries to pop another conditional, but the stack is empty, so the program crashes.
> 5 votes

# Answer
## Haskell, 15 bytes

```
f(a:b)=f b
f"a"

```

`f"a"` runs recursively through the string "a" by dropping the first char and eventually fails at its end with a `Non-exhaustive patterns in function f` exception, because `f` is only defined for non-empty strings.
> 5 votes

# Answer
# Pyth, 3 bytes

```
W1w

```

Try it online.

`W1` is just `while 1:` in Python. The loop body prints a line read from STDIN, which crashes for the second iteration when the code is run with empty input.

If loops using `#` (loop-until-error) are banned (I assume so), I think this is the shortest it can get.
> 5 votes

# Answer
# JavaScript, 9 bytes

```
for(;;i);

```

This runs once, then throws `ReferenceError: i is not defined` which stops the loop.

```
// With a console.log(1) to see that it runs once.
for(;;i)console.log(1);
```

---

Taking the following as an example, is the `<increment>` the end of the first cycle or the beginning of the second cycle ?

```
0:for(<init>;<test>;<increment>)
1:{
2:  <statement>;
3:}

```

### 1/ I see it

After going from lines 0 to line 3 then going **back** to line 0, it feels like a full cycle has been completed.
That would make the `<increment>` the beginning of the second cycle.
\- First cycle : `<init>` -\> `<test>` -\> `<statement>`
\- Second cycle : `<increment>` -\> `<test>` -\> `<statement>`

### 2/ `While` equivalent

```
0:<init>;
1:while(<test>)
2:{
3:  <statement>;
4:  <increment>;
5:}

```

In this equivalent `while` the `<increment>` is the end of the first cycle and it feels like it's the same with the `for`.
That would make the `<increment>` the end of the first cycle.
\- First cycle : `<test>` -\> `<statement>` -\> `<increment>`
\- Second cycle : `<test>` -\> `<statement>` -\> `<increment>`

### 3/ A statement is encountered twice

A full cycle is completed when a statement is encountered twice.
The first statement encountered twice is `<test>`.
That would make the `<increment>` the end of the first cycle.
\- First cycle : `<test>` -\> `<statement>` -\> `<increment>`
\- Second cycle : `<test>` -\> `<statement>` -\> `<increment>`

### 4/ It's a setup

The `<init>` is just setting up whatever is needed for the first cycle.
The `<increment>` is just setting up whatever is needed for the second cycle.
That would make the `<increment>` the beginning of the second cycle.
\- First cycle : `<init as a setup>` -\> `<test>` -\> `<statement>`
\- Second cycle : `<increment as a setup>` -\> `<test>` -\> `<statement>`

---

The ECMAScript® 2016 Language Specification

Runtime of `for(<init>;<test>;<increment>)<statement>;`

> Let varDcl be the result of evaluating `<init>`.
> ReturnIfAbrupt(varDcl).
> Return ? ForBodyEvaluation(`<test>`, `<increment>`, `<statement>`, « », labelSet).

There are three forms, so I took the shortest one here, there's no difference:
\- Whatever the `<init>` it isn't part of the first iteration.
\- What's relevant is in ForBodyEvaluation.

Details of ForBodyEvaluation(`<test>`, `<increment>`, `<statement>`, « », labelSet)

> 0 Let V be undefined.
> 1 Perform ? CreatePerIterationEnvironment(perIterationBindings).
> 2 Repeat
> 3 If is not \[empty\], then
> 4 Let testRef be the result of evaluating `<test>`.
> 5 Let testValue be ? GetValue(testRef).
> 6 If ToBoolean(testValue) is false, return NormalCompletion(V).
> 7 Let result be the result of evaluating `<statement>`.
> 8 If LoopContinues(result, labelSet) is false, return Completion(UpdateEmpty(result, V)).
> 9 If result.\[\[Value\]\] is not empty, let V be result.\[\[Value\]\].
> 10 Perform ? CreatePerIterationEnvironment(perIterationBindings).
> 11 If is not \[empty\], then
> 12 Let incRef be the result of evaluating `<increment>`.
> 13 Perform ? GetValue(incRef).

### 6/ I see it

A full cycle a full run of the repeat part.
That would make the `<increment>` the end of the first cycle.
\- First cycle : `<test>` -\> `<statement>` -\> `<increment>` / In other words from line 3 to line 13
\- Second cycle : `<test>` -\> `<statement>` -\> `<increment>` / In other words from line 3 to line 13

### 7/ A cycle is an iteration

A cycle begin with `CreatePerIterationEnvironment`.
So when `CreatePerIterationEnvironment` is encountered a new cycle begins, thus ending the previous one.
That would make the `<increment>` the beginning of the second cycle.
\- First cycle : `<test>` -\> `<statement>` / In other words from line 1 to line 9
\- Second cycle : `<increment>` -\> `<test>` -\> `<statement>` / In other words from line 10 looping until line 9

---

Is the `<increment>` the end of the first cycle or the beginning of the second cycle?

> The right explanation is either 6 or 7.
> 5 votes

# Answer
# C#, ~~71~~ 38 bytes

Since you provided an example in C# here another version golfed

And thanks to pinkfloydx33

```
void c(){checked{for(uint i=1;;i--);}}

```

Shorter than `Parse.ToString()` and even than `Parse($"{c--}")` I mentally dumped `checked` for it being too long of a keyword. Tough it certainly is shorter than `Parse(c.ToString())`

# Original answer

```
class p{static void Main(){for(int c=0;;c--)uint.Parse(c.ToString());}}

```

This will start `c=0` then decrement it, when `c=-1` the `uint.Parse` will cause an:

```
Unhandled Exception: System.OverflowException: Value was either too large or too small for a UInt32.

```

Ungolfed version and verifying that loop runs at least once

```
class p {
    static void Main() {
        for(int c=0;;c--) {
            System.Console.Write(c);
            uint.Parse(c.ToString());
        }
    }
}

```
> 5 votes

# Answer
# CJam, 4 bytes

```
P`:~

```

`P``  generates the string `3.141592653589793`. `:~` evaluates each character. `3` is valid code in CJam which simply returns 3. In the next iteration, `.` causes an error because it requires a digit or an operator following it.
> 5 votes

# Answer
### x86 assembly (AT&T syntax), 40 bytes

```
f:
mov $1,%eax
A:
div %eax
dec %eax
je A

```

Declares a function f which divides 1 by 1 on its first iteration then attempts to divide 0 by 0 and errors.
> 4 votes

# Answer
## \>\<\>, 3 bytes

```
!]!

```

Try it here!

### Explanation

```
!    skip next instruction
 ]   close stack (crash)
  !  skip next instruction (jumping to close stack)

```
> 4 votes

# Answer
# INTERCAL, 12 bytes

```
(1)DO(1)NEXT

```

Try it online!

`NEXT` is INTERCAL-72's main control flow command. (Later revisions introduced `COME FROM`, which became more famous, but it wasn't in the original version of the language; and all finished INTERCAL implementations I'm aware of support `NEXT` for backwards compatibility, with all but one enabling support for it by default. So I don't feel the need to name INTERCAL-72 specifically in the title.)

When using `NEXT` to form a loop, you're supposed to use `RESUME` or `FORGET` in order to free up the space that it uses to remember where the program has been; `RESUME` retroactively makes the `NEXT` into something akin to a function call (although you can return from functions other than the one you're in) whereas `FORGET` makes it into something more similar to a GOTO statement. If you don't do either (and this program doesn't), the program will crash after 80 iterations (this behaviour is actually specified in the INTERCAL specification).

It's somewhat ambiguous whether this counts as unbounded recursion (disallowed in the question); you can certainly use this sort of `NEXT` to implement a function call, in which case it would effectively be a recursive function, but there's not enough information here to determine whether we're doing a function call or not. At least, I'm posting this anyway because it doesn't unambiguously violate the rules, and an INTERCAL implementation that optimized out the "tail call" would not only violate the specification, but also cause most existing programs to break, because returning from the "wrong function" is the main way to do the equivalent of an IF statement.

Here's the resulting error message, as generated by C-INTERCAL:

```
ICL123I PROGRAM HAS DISAPPEARED INTO THE BLACK LAGOON
    ON THE WAY TO 1
        CORRECT SOURCE AND RESUBNIT

```

(Note that the second line is indented with a tab, and the third with eight spaces. This looks correct in a terminal, or in pretty much any program that has tab stops at multiples of 8. However, Markdown has tab stops at multiples of four, violating the assumptions that most older programs make about tabs, so the error message is a little malformatted here.)
> 4 votes

# Answer
## Ruby, 14 Bytes

```
loop{$./=~$.}

```

Exits due to `ZeroDivisionError: divided by 0`

`$. The current input line number of the last file that was read`

Ruby Docs
> 4 votes

# Answer
# Batch, ~~22~~ 20 bytes

```
:a
set i=%i%1
goto a

```

**Explanation**

This is an infinite loop that appends a `1` onto an initially empty string. Eventually this will pass the maximum string length of 8192 and crash. On my machine, this takes about 30 seconds.
> 4 votes

# Answer
# Rust, 23 bytes

```
||for i in 0..{[()][i]}

```

Try it online!

Similar to TehPers's answer, but using a unit type array instead of a string gets rid of the `&`, `..` and `;`
> 4 votes

# Answer
## Python 3, 29 bytes

```
i=1
def x(n):del i;x(i)
x(i)

```

Really simple. On the second call to x, i isn't there, and Python complains about it.
> 3 votes

# Answer
## Labyrinth, 3 bytes

```
#(/

```

Try it online!

Like most 2D languages, Labyrinth doesn't have any explicit looping constructs. Instead, any code that is laid out such that it is executed multiple times in a row is a loop in these languages. For the case of Labyrinth, a simple linear program acts as a loop, because the instruction pointer will bounce back and forth on it. If the program is `abc` (for some commands `a`, `b` and `c`), then the actual execution will be `abcbabcbabcb...` so it runs `abcb` in an infinite loop.

As for why this particular program crashes on the second iteration of this loop, here is what the individual commands do. Note that Labyrinth's stack contains an implicit infinite amount of zeros at the bottom:

```
#   Push stack depth.   [... 0]
(   Decrement.          [... -1]
/   Divide.             [... 0]
(   Decrement.          [... -1]
#   Push stack depth.   [... -1 1]
(   Decrement.          [... -1 0]
/   Divide.             Crashes with division-by-zero error.

```
> 3 votes

# Answer
# Bash, 11 (Borderline non-competing)

```
exec $0 1$@

```

This script recursively execs itself, appending `1` to the args passed on each iteration. I think this counts as TCO because exec reuses the process space but doesn't eat up stack. It is borderline non-competing because it took about 10 minutes before being killed on my machine - YMMV.
> 3 votes

# Answer
## QBIC, ~~14~~ 9 bytes

I've ported @Dlosc 's approach to QBIC, giving me a 9-byte loop-to-crash:

```
[12|?b(a)

```

This prints elements 1 through 12 of the non-existant array `b` and since QBasic gives us a blank 10-spaced array when first calling `b(i)` with a free eleventh slot (that's 10% EXTRA!), it fails on index 12.

---

Original answr:

```
[256|?chr$$(a)

```

This starts a FOR-loop that runs 256 times. On each iteration the FOR-loop counter is cast to an ASCII character and printed to screen. However, `256` is invalid in the ASCII table and `CHR$()` throws an error.
> 3 votes

# Answer
# cmd, 34 bytes

```
for /l %i in (0,1,10) do color %i0

```

This will cycle `%i` from 0 to 10. The (ancient) `color` command will happily accept any argument that has 2 (hexa-)decimal digits. With the argument `100` it will fail, printing the the help message and setting `ERRORLEVEL` to 1.

Proof of the loop running at least once: The color of your shell will be different!
> 3 votes

# Answer
# Octave, ~~30~~ 23 bytes

*Thanks to @StewieGriffin for golfing off 7 bytes!*

```
for i=32:35,eval(i),end

```

Try it online!

I was inspired by this Octave answer where `eval` was used in a similar fashion.

### Old answer

```
for i=101:105;eval([i]);endfor

```

Note: my Octave knowledge is very little, so my explanation might be slightly off.

This for-loop completes 1 iteration, after that (on the second one) a `error: 'f' undefined near line 1 column 1` is thrown.

`eval([number])` evaluates the ASCII literal represented by the character code. On the first iteration, it runs `eval([101])`, which is the same as `eval(e)`, Euler's Constant. And so the value of `e` gets displayed (`2.7183`). On the next iteration, the program runs `eval([102])`, ie `eval(f)`, and this throws and error since `f` is not defined. After this, the program halts and no more iterations are run.
> 3 votes

# Answer
# Java (JDK), 26 bytes

```
v->{for(int a=9;;a/=--a);}

```

Try it online!

Dummy division by zero at the end of the second loop.

## Credits

* -1 byte thanks to Benjamin Urquhart
> 3 votes

# Answer
# Dyalog APL, 4 bytes

```
*⍣=0

```

*x*0 = 0, *x*1 = *e*x0, *x*2 = *e*x1,... until two successive values are equal (i.e. never). Hits a DOMAIN ERROR on the fifth loop, as decimal128 floats overflow.

This hits the same error only on the 12361st loop (about 8 ms on my laptop):

```
○⍣=1

```

*x*0 = 2, *x*1 = x0*π*, *x*2 = x1*π*,... until two successive terms are equal (never).
> 3 votes

# Answer
# Fuzzy Octo Guacamole, 5 bytes

```
11(/)

```

Pushes `1` twice, then starts looping. Divides the first one by the other one, consuming them. Then tries to divide 1 by 0, erroring and exiting.
> 3 votes

# Answer
# Perl 5, 19 12 bytes

```
0/$_ for 1,0

```

I translated sonrad10's answer to Perl.

Output:

```
Illegal division by zero at - line 1.

```

Previously (19 bytes): `$n=1;{$n/$n--;redo}`

## Testing and explanation

```
$| = 1;     # Forces print flushing, no buffering.
$i = 0;     # Iteration counter for debugging.
$SIG{ALRM} =    # Set SIGALRM signal handler.
    sub {       # Anonymous subroutine, or function.
        die "2-second timeout reached!";
    };
alarm($timeout = 2);    # SIGALRM will be sent 2 seconds from now.

##############################
### Dividing `0 / $n--`... ###
##############################
for (1, 0) {
    print 'Iteration '.++$i."; n = $_.\n";
    0 / $_;
}

```

Output:

```
Iteration 1; n = 1.
Iteration 2; n = 0.
Illegal division by zero at test.pl line 14.

```
> 3 votes

# Answer
# x86 machine code on DOS - 4 bytes

Played really straight:

```
00000000  f7 f1 e2 fc                                       |....|
00000004

```

Which is just:

```
    org 100h

section .text

start:
    div cx
    loop start

```

`cx` starts at whatever value; loops as long as `cx` is not zero - and when it's zero, it crashes due to a division by zero.

Notice that this won't work directly in DosBox (whose interpreter, for reasons I don't understand, doesn't handle the CPU exception and just hangs). In a real DOS/Windows 3.11 VM (and probably in DosBox with "original" `command.com`) it crashes just fine.
> 3 votes

# Answer
# √ å ı ¥ ® Ï Ø ¿ , 6 bytes

```
X2[P]

```

Tries to pop from an empty list and fails

## Explanation

```
X     › Push 10 to the stack
 2    › Push 2 to the stack
  [   › Start a for loop that iterates 2 times (pop the top value)
   P  › Pop the top value
    ] › End for loop

Command | Stack
--------+-------
   X    |  10
   2    |  2,10
   [    |  10
   P    |  None   (1st iteration)
   P    |  ERROR (2nd iteration; cannot pop from empty list)
   ]    |  None

```
> 3 votes

# Answer
# Commodore BASIC (C64Mini, C64, VIC-20, C128 etc..) 32 27 25 tonekized BASIC bytes

```
0FORI=9TO0STEP-1:PRINTI/I*I:NEXT

```

As it counts down, it will produce a `?DIVISION BY ZERO ERROR IN 0` error before it hits `0` as is intended (old 32 byte solution shown in associated image).

### CBM BASIC (Direct mode) 9 bytes used on stack, 31 PETSCII characters

```
FORI=9TO0STEP-1:PRINTI/I*I:NEXT

```

It's a bit difficult to determine the amount of memory used in direct mode as no program is stored so that saves on those BASIC tonkenized bytes, also it executes by calling via the Kernal so that's ROM not RAM; the BASIC screen is default to 1000 bytes and direct mode outputs 1 8-bit character per line + white space + carriage return. When I request the free bytes, it tells me that I've used 9 so I'll go with that (I think that includes some memory pointers as well).
> 3 votes

# Answer
## Haskell, 13 bytes

```
f a=f$f a
f 1

```

Runs out of memory after a while.
> 2 votes

# Answer
# Sesos, 2 bytes

```
00000000: 0846                                              .F

```

Try it online!

### Sesos assembly

The binary has been generated suing the following SASM code.

```
nop, put, sub 1

```

This enters a do-while loop (`nop`), prints a NUL character (`put`), decrements the memory cell (`sub 1`) and starts over. In the second iteration, `put` tries to cast **-1** to character, which fails and aborts execution with the following error message.

```
Invalid code point (-1) for encoding UTF-8.

```
> 2 votes

# Answer
# Brainfuck, 5 bytes

```
+[>+]

```

Increments the current cell. While the current cell is non-zero, move to the next cell and increment it. Since all cells start as zero, this is logically an infinite loop, but on implementations with finite tape, aborts when the end of the tape is reached. With `bf`:

> Error: Out of range! You wanted to '\>' beyond the last cell.See -c option.
> an error occured
> 2 votes

# Answer
# Java, 73 bytes

```
interface A{static void main(String[]a){for(int i=0;;)if(i>0)a[i++]="";}}

```

Will error out with `ArrayIndexOutOfBoundsException`.
> 2 votes

# Answer
# , 1 byte (of which only 3 bits are used)

In octal encoding:

```
4

```

In binary encoding (CP437):

```
ƒ

```

This program works as follows (as usual in my 7 demonstrations, the anonymous commands are named the same way as the corresponding named commands, and I use syntax highlighting to differentiate; bold means active, nonbold means passive):

```
Frame    Program   Interpretation of the program
||       4         Append **4** to the frame
||**4**      (empty)   Copy the last section of the frame to the program
||**4**      **4**         Swap last two frame sections, add an empty section between
|**4**||     (empty)   Discard last empty frame section
|**4**|      (empty)   Discard last empty frame section
|**4**       (empty)   Copy the last section of the frame to the program
|**4**       **4**         Swap last two frame sections, add an empty section between
**4**||      (empty)   Discard last empty frame section
**4**|       (empty)   Discard last empty frame section
**4**        (empty)   Error: program is empty, frame contains no bar

```

Try it online!

What we effectively have by ending the program with **`4`** is a loop that executes each stack element in turn, giving it itself as an argument. The initial stack contains two empty elements, so we get through two iterations before the program crashes due to a malformed stack.
> 2 votes

# Answer
## Clojure, 25 bytes

```
(iterate #(do(% 0)[])[0])

```

Implicit loop using `iterate`. Starts with a non-empty list, accesses the first element, then replaces the accumulator with an empty list. During the next iteration, it crashes with an index out of bounds exception when it tries to access the first element again.

This appears to be as short as it gets. I'd love to see someone beat this in Clojure.
> 2 votes

# Answer
## Lua, 11 bytes

Suprised, such a short Lua answer.

```
::a::goto a

```

On ideone it exceeds the time limit of 5 seconds, locally it freezes the interpreter window in about 5-30 seconds.

```
::a:: --Define GOTO point
goto a --Endlessly loop back there, without waiting.

```
> 2 votes

# Answer
# PowerShell, 18 bytes

```
0,1|%{rv ~ -ea $_}

```

Try it online!

### Explanation

An array with two elements, `0` and `1`, is piped into `ForEach-Object` (`%`). Within the loop we try to remove a non-existant variable named `~` (it could have been named anything that doesn't exist).

By default this is a non-terminating error, but we're setting the `-ErrorAction` (`-ea`) to be equal to the loop object. So on the first run it's `0` which corresponds to `SilentlyContinue` (it won't even show the error text), then on the second run it's `1` which corresponds to `Stop`; this makes the error terminating, so the program will exit since this exception is unhandled.
> 2 votes

# Answer
## Python 20 Bytes

```
def f(x=1): f(x/x-1)

```

When called defaults x to 1 and finds 1/1-1=0 it then finds 0/0-1 and throws an error.
> 2 votes

# Answer
## memes, 3 bytes

```
n1´

```

Will attempt to recurse infinite times (lower `-1` until its `0`).

```
n1      Negative one
´       Loop that many times

```

This works because the looping mechanism takes the specified number, and decreases it until it is 0 – `-1` therefore provides infinity. Will crash when the loop index is too large, assuming it doesn't freeze beforehand.
> 2 votes

# Answer
# PHP, ~~16~~ 13 bytes

Quite simply:

```
while($o.=a);

```

Fast (original) version (16 bytes):

```
while($o.=a.$o);

```

Run like this (notices hidden because output to screen is slow):

```
php -d error_reporting=30709 -r 'while($o.=a);'

```

# Explanation

Just suffix a variable with `a` until the memory limit is exhausted (fatal error). This takes less than a minute on my machine.

Original (fast) version only needs a couple (20 something) iterations because the string grows exponentially.
> 2 votes

# Answer
# C#, ~~30~~ 27 bytes

Saved 3 bytes, thanks to milk

```
b=>{for(int i=3;;)i/=--i;};

```

It runs once, and then divides zero by zero.
> 2 votes

# Answer
**x86 Assembly, 18 bytes**

```
jmp start
ReadEIP:
mov eax,[esp]
ret
start:
call ReadEIP
db 90h
mov bl,91h
mov [eax],bl
jmp start

```

Bytes: `Ù♦ï♦$├Þ¸   É│æê↑Ù¶`

Hexadecimal: `['0xeb', '0x4', '0x8b', '0x4', '0x24', '0xc3', '0xe8', '0xf7', '0xff', '0xff', '0xff', '0x90', '0xb3', '0x91', '0x88', '0x18', '0xeb', '0xf4']`

This is a silly method, but I like it. I'm amazed about the other answer simply using "div cx", which I didn't even think of.

Anyhow, what this does is read out EIP (the instruction pointer), which points at the next byte, "db 90h". That's simply a NOP instruction, which does nothing. Before I had "inc bl", but I realized that simply changing the byte to something else is sufficient and needs two bytes less.

The first time the loop runs it goes through the loop, executing the NOP. The second time the 90h is a 91h, which throws an exception.
> 2 votes

# Answer
# TI-Basic, 5 bytes

```
Repeat ln(0:End

```

The key here is that in TI-Basic, `Repeat` loops only evaluate the conditional expression starting with the second iteration.
> 2 votes

# Answer
**AT&T x86 assembly, 3 instructions, division by zero**

```
.global main
main:
    div %eax
    dec %eax
    jmp main

```

**AT&T x86 assembly, 3 instructions, segfault**

```
.global main
main:
    inc %eax
    mov %eax, (%eax)
    jmp main

```
> 2 votes

# Answer
# tcl, 22

```
time {rename time t} 2

```

`time` is a function to measure how much time is elapsed on a script. As it can receive a parameter on how many times to repeat to get the time measure of each one, it can be used has a looping mechanism.

Enters the loop, executes the renaming of `time` command to `t`, then can not execute the 2nd iteration because `time` command went away!

# tcl, 24

```
while 1 {rename while w}

```

Enters the loop, executes the renaming of `while` command to `w`, then can not execute the 2nd iteration because `while` command went away!

# tcl, 26

The `for` version is two more bytes longer.

```
for {} 1 {} {rename for f}

```
> 2 votes

# Answer
# Japt, 5 bytes

```
1/0 o

```

Try it online!

### How it works

```
1/0   Infinity
o     Try to create the range [0..Infinity] as an array

```

The range array consumes most of the JS engine's memory space in about 2s, and finally exits with `fatal error: heap out of memory`.

---

The following would work if simple recursion was allowed.

# Japt, 1 byte

```
ß

```

Try it online!

`ß` calls the entire program recursively, and the infinite recursion quickly results in stack overflow.
> 2 votes

# Answer
# Forth (gforth), 19 bytes

```
: f 0 begin until ;

```

Try it online!

### Explanation

The first iteration of the loop consumes the 0 on the stack, causing the second iteration to fail with a stack-underflow while trying to grab the top of the stack.

### Code Explanation

```
: f        \ Begin a new word definition
   0       \ place a 0 on the stack
   begin   \ start an indefinite loop
   until   \ grab the top of the stack and end the loop if not 0
;          \ end the word definition

```
> 2 votes

# Answer
# C, 23 bytes

-1 bytes thanks to ceilingcat
Division by zero is boring

```
main(){for(;;free(1));}

```

Segfaults after the first iteration

TIO
> 2 votes

# Answer
# Deadfish~, 5 bytes

```
{isc}

```

Try it online!

This tries to follow the instructions "increment, square, print as a character" 10 times. As soon as a value greater than 255 is reached (which is 676 on the fourth iteration), it crashes trying to print a character value that does not exist.
> 2 votes

# Answer
# Runic Enchantments, 2 bytes

```
`;

```

Try it online!

Repeatedly pushes a `;` character onto the stack until the stack is too large and the IP begins fizzling and eventually runs out of mana and is terminated (about 24 full loops).
> 2 votes

# Answer
# x86 Machine Code, 3 bytes

Same size on both 64 or 32 bit. 2 instructions.

```
a:pushf
jmp a

```

In 64-bit or 32-bit:

```
Dump of assembler code for function a:
   0x0000000000001000 <+0>: 9c  pushfq
   0x0000000000001001 <+1>: eb fd   jmp    0x1000 <a>
End of assembler dump.

```

Same machine code. Obviously, the 32-bit version won't have the extra 0's in front of the address or the `q` suffix.

It just runs out of stack space.
> 2 votes

# Answer
# Mornington Crescent, ~~238~~ 215 bytes

```
Take Northern Line to Bank
Take Circle Line to Temple
Take District Line to Parsons Green
Take District Line to Notting Hill Gate
Take District Line to Mile End
Take District Line to Bank
Take Northern Line to Angel

```

Executing the final line of the program jumps the program back to the second line, thus constituting the only way to loop in Mornington Crescent. After a few swaps of the accumulator and various stations, in the second iteration of the loop, the program attempts to find the last `-1` characters of the empty string `""`. Since `-1` is clearly out of range, a runtime error is thrown.

There are other runtime errors that could beget a shorter solution, such as not ending at Mornington Crescent, but I decided those were too trivial to really count.

EDIT: Fiddling around with the order yields a slightly shorter solution.

Try it online!
> 2 votes

# Answer
# Rust, 25 bytes

```
||for i in 0..{&""[i..];}

```

Try it online

This tries to slice the empty string "" by the current loop index. The first iteration is successful, but the second panics because the string is empty.
> 2 votes

# Answer
# 1+, 7 bytes

```
1(|:())

```

1+ answer delivery service, sign here.

## Explaination

`1` pushes 1 onto the stack. The rest of the program (which looked like a fancy emoticon) defines a recursive function with an empty name that repeatedly pop and output the stack top, so you'll pop an empty stack the second time, which is invalid. 1+ functions are executed while defined.
> 2 votes

# Answer
## Ruby, 17 bytes

```
2.times{|i|i/~-i}

```
> 1 votes

# Answer
# SMBF, 5 bytes

Runs the loop once, then modifies the source code, exiting the loop. The instructions reached, in order, are: `+[-<][-<\`.

```
+[-<]

```

The test runs on the TIO interpreter, but you can't really check what happens. Visit the first hyperlink, which is my Python interpreter. Change the code on the `data = bytearray(...` line. The interpreter used to take code from STDIN, but I found that I needed non-printable input so often that changing the input in the source is easier. I also just added an option for recording what instructions were executed, which you can enable by changing `debug=True`.
> 1 votes

# Answer
# bash (No recursion), 20 bytes

```
for((;;)){ x=x$x$x;}

```

This one crashes on my machine in just over a minute, due to running out of memory.

---

If you get rid of the 2-minute rule, presumably

```
for((;;)){ x=x$x;}

```

(18 bytes) will eventually crash due to running out of memory, but it will take a *long* time.

---

I had originally posted a recursive solution in 10 bytes:

```
f()(f;:);f

```

This 10-byte program crashes on my MacBook in about half a second with a "fork: Resource temporarily unavailable" error. There's no tail-recursion to optimize away, since the last thing done in each call is the ":" command, not the recursive subcall.

But @Dennis pointed out that this doesn't satisfy Rule 4 (the program must complete one full cycle), since none of the recursive calls actually get a chance to complete before the program crashes.

I think this same problem invalidates other recursive programs that have been posted as answers.

---

By the way, if you allow tail recursion, you can do it in 8 bytes:

```
f()(f);f

```

\[This version doesn't satisfy the tail-call-optimization requirement, and it's arguable whether it satisfies the one-complete-cycle rule. The function calls (except for the last) execute all of the code in their body, but they don't ever return. So if "one complete cycle" means one complete body, not including the return at the end, it's OK for Rule 4. If "one complete cycle" is taken to include the return at the end, then Rule 4 is not satisfied.\]
> 1 votes

# Answer
# Python 3, 35 Bytes

```
x=lambda a:1/0if a<1 else x(0);x(2)

```

I am not totally sure, but I think this works like you'd expect. Does that count as an true answer?
> 1 votes

# Answer
# Factor, 19 bytes

```
1 iota [ 0 / ] each

```

Fails with 0 division error after 1 run.
> 1 votes

# Answer
## Go, 28 bytes

```
func f(){i:=1;for{i/=i;i--}}

```

Simple divide by zero
> 1 votes

# Answer
# Mathematica, ~~22~~ 19 bytes

*3 bytes saved due to Martin Ender.*

```
#>0&&Throw@#&/@{0,}

```

Uses `Throw@#` to throw an exception when looping over the second element. I can't think of anything else that would cause the program to immediately stop.
> 1 votes

# Answer
## awk 18 bytes

```
{while(++i/i)i-=2}

```

or using `for`:

```
{for(;++i/i;)i-=2}

```

Test it (added `print` for iteration proof):

```
$ awk '{while(++i/i){print i; i-=2}}' /dev/urandom
1
awk: cmd. line:1: (FILENAME=/dev/urandom FNR=1) fatal: division by zero attempted

```
> 1 votes

# Answer
# Turtlèd, 6 bytes

runs one cycle before crashing. however it produces no output, because the interpreter does the crash before it prints the grid.

```
[|(*r]

```

**Tryitonline** can show you the error in debug, but won't really show you whether it runs the loop one cycle and a half, but if you want, you could download the interpreter, modify command `]` to print `howdy` or something, and see that it prints `howdy` prior to crashing.

yes, the parentheses is usually in pairs for ifs. looks like a syntax error, but my language checks no syntax

## How it works:

So this is a turtle based language, moving around on an infinite grid of cells with chars in

Firstly, there is the infinite loop

```
[|   ]

```

this loop runs while the cell does not have a |. There is no way that a cell will contain a |, since no code in this writes it or user input down, so this would run forever (except error)

The code inside:

```
(*r

```

the `(*` would usually starts an if block. essentially, if the current cell is a `*`, do nothing and continue running, otherwise skip ahead to the matching `)`, and the `r` just makes the pointer move right.

on the first cycle, the turtle starts in the centre cell, which unlike other cells, begins as an `*`.

here are the steps of execution from there

* the infinite loop starts running.
* checks the current cell to see if it is an asterisk, sees it is
* moves right, off the asterisk cell
* loops back to the start of loop
* checks if cell is an asterisk. it is a space, so it tries to skip ahead
* interpreter throws IndexError, because it tried to look past the end of the loop for the closing `)`
> 1 votes

# Answer
# Valve Scripting Language, 21 bytes

```
alias a "alias a b;a"

```

This creates a function that will recurse when called. You can call the function just by typing 'a' into the console.

Since this challenge wants an error to be thrown, `b` is sufficient. This will just error with undefined function. However, you can also replace `b` with `quit` to fully quit the application.

Explanation for those who don't immediately understand: it re-aliases the function to something that doesn't exist.
> 1 votes

# Answer
# Bash, 21 bytes

```
alias a="alias a=c;a"

```

Same logic as my VSL answer, posted for completeness.
> 1 votes

# Answer
# Ruby, 11 bytes

```
loop{$.*=2}

```

`$.` needs to be a long, so it will throw after a couple cycles.
> 1 votes

# Answer
# Julia, 19 bytes

```
for i=1:2 "a"[i]end

```

The first loop accesses string `"a"` at index `[1]`, which is char `'a'`, the second loop tries to access string "a" at index `[2]` and throws a `BoundsError`:

```
julia> for i=1:2 "a"[i]end
ERROR: BoundsError: attempt to access 1-element Array{UInt8,1} at index [2]
 in next at .\strings\string.jl:88 [inlined]
 in getindex(::String, ::Int64) at .\strings\basic.jl:70
 in macro expansion; at .\REPL[40]:1 [inlined]
 in anonymous at .\<missing>:?

```
> 1 votes

# Answer
# DUP, 10 bytes (8 chars)

Conor O'Brien already wrote the shortest possible solution in FALSE which is also a valid DUP program. DUP is a direct descendant of FALSE and FALSE is almost a complete subset of DUP, with a few exceptions. I won’t just simply rip off his solution but add a slightly bigger (in bytes, not chars) but specific DUP solution just for the fun of it:

```
1[.A]⇒AA

```

In contrast to FALSE, DUP can define/redefine operators with the (3 UTF-8 byte)  operator. Operator names are not bound to the lowercase ASCII range of variables but can use the whole Unicode range of characters.

This solution is a recursive operator call that throws an error after the first recursive call of itself:

```
1[.A]⇒AA     data   return
             stack  stack

1                            push 1 on data stack
 [           1               push [ location on data stack, move behind matching ]
     ⇒A       1,1            pop data stack, assign value (function location) to function A
       A      1              call function A, push current ip location on return stack,
                             move ip 1 behind stored address in A (1)
  .           1      7       pop data stack, print value to STDOUT
   A                         call function A, move ip 1 behind stored address
  .                          pop data stack... throws error because the data stack is empty.

```

Try it out in the online DUP interpreter on quirkster.com or clone my DUP interpreter repository on GitHub (written in Julia).
> 1 votes

# Answer
# Kotlin, 19 bytes

```
{for(x in-1..0)1/x}

```

A simple lambda expression that does one iteration of the for loop and then throws with a division by zero exception.
> 1 votes

# Answer
## Euphoria \- 53 bytes

```
atom i
i=1
while 1 do
puts(i,i)
i-=1
end while

```

Did it in a different way so we dont get full of "division by 0" errors.

**Explanation:**

"puts" first argument is the device to output argument two. There are three pre-defined devices:

> 0 is STDIN, 1 is STDOUT, and 2 is STDERR

After decreasing i (with `i-=1`) once, on the second cycle we will get

> Wrong file mode for attempted operation

which is the exception/error.
> 1 votes

# Answer
# Swift, 22 bytes

```
for i in 0...1{[0][i]}

```

Pretty self-explanatory, crashes with sigill on second iteration. You can do the exact same thing in Python with 2 less bytes, but I really wanted to do a Swift submission.

Try it online!
> 1 votes

# Answer
## Clojure, 21 bytes

Quite odd challenge, I hope I understood this correctly. On first iteration `i` is the `+` function which can be called with zero arguments and it returns zero, on second iteration `(0)` is evaluated and you get `ClassCastException java.lang.Long cannot be cast to clojure.lang.IFn`.

```
(loop[i +](recur(i)))

```

Confirmation that loop is executed twice:

```
(loop[i +](do(print{:i i})(recur(i))))
{:i #object[clojure.core$_PLUS_ 0x7e72f43f clojure.core$_PLUS_@7e72f43f]}
{:i 0}

```
> 1 votes

# Answer
# Dart, 20 bytes

```
_ i=1;for(;;)0~/i--;

```

Since Dart discards static type information at runtime, declaring a variable with an unknown type ( `_` ) gives a warning but doesn't stop the code from running. Then we just trigger an exception by doing integer divide by 0.

### Bonus 1, 23 bytes

```
_ x;for(;;)x=x?.a??"x";

```

Same thing as above, but it doesn't utilize a floating point exception. It uses the "null operator" on x to access member a, which evaluates to null when x is null and throws a runtime error when x is not null but doesn't have the property x. We also use the "??" operator to coerce the null value from x?.a to "x". Strings don't have a property named "a", so it errors.

### Bonus 2, 22 bytes

```
_ x=(){};for(;;)x=x();

```

This declares an anonymous function that returns void, which actually return null (since everything is nullable in Dart). The first loop iteration gets a successful call and sets x to null. The second loop iteration errors because the Null type doesn't have a call method.

Edit: To clarify, the warning given above is not from Dart but from Dart's analyzer (so its a pre-runtime warning).
> 1 votes

# Answer
# SmileBASIC, 15 bytes

```
EXEC.>SPSET(0)W

```
> 1 votes

# Answer
# C#, 23 bytes

### Out of range (23 bytes):

```
()=>{while(""[1]>'a');}

```

### Divide by zero (25 bytes):

```
()=>{for(int i=0;;i/=i);}

```

### Runtime binder exception (33 bytes):

```
()=>{for(;;){dynamic d=1;d.D();}}

```

### Null reference (36 bytes):

```
()=>{string x=null;while(x[1]>'a');}

```

### Stackoverflow (C# 7 local function) (37 bytes):

```
()=>{while(true){bool b()=>b();b();}}

```

### Argument exception (48 bytes):

```
()=>{while(System.IO.File.ReadAllText("")=="");}

```

### Invalid operation (77 bytes):

```
()=>{var v=new System.Collections.Generic.List<int>{1};v.ForEach(V=>v[0]=0);}

```
> 1 votes

# Answer
# HQ9+-, 2 bytes

`Q-`

The program consists of two parts:

* `Q`\- Prints out the source code (which, in this case, is `Q-`).
* `-` Behavior changes based on the previous character(s) in the program. Since `Q` came before `-`, the program enters into a recursive loop and finally quits, raising the error:

`[1] 1979 segmentation fault ./hq9+-i test.hq9`
> 1 votes

# Answer
## Underload, 13 bytes

```
(!a(:^)*^)::^

```

Try it online!

Stack trace:

```
(...)   | (!a(:^)*^)
:       | (!a(:^)*^)(!a(:^)*^)
:       | (!a(:^)*^)(!a(:^)*^)(!a(:^)*^)
^       | (!a(:^)*^)(!a(:^)*^)
 !      | (!a(:^)*^)
 a      | ((!a(:^)*^))
 (...)  | ((!a(:^)*^))(:^)
 *      | ((!a(:^)*^):^)
 ^      |
  (...) | (!a(:^)*^)
  :     | (!a(:^)*^)(!a(:^)*^)
  ^     | (!a(:^)*^)
   !    |
   a    | <error>

```

Underload is interesting. The only way to loop is to create a sort of quine. The basic idea is this:

* Push a block containing the loop body to the stack: `(...)`
* Duplicate it, and then execute it. This means the loop body will be run with the loop body string at the bottom of the stack: `(...):^`
* In the loop body, immediately "uneval" with the `a` command: `(a...):^`
* Append `:^` to the end: `(a(:^)*...):^`. This recovers the original program (and in fact, if we output right here, we would have a quine.)
* Execute this stack value to loop: `(a(:^)*^):^`. This is the basic structure of our loop program.

I've made a few changes to this idea. The first is that we duplicate twice rather than once before entering the loop. Normally, this would not be significant (as we would just have an unused value at the bottom of the stack) but I also add a `!` (delete) at the beginning of the loop body, which means that the stack will be gradually "worn down." After two iterations of the loop, the stack is empty, so running `a` causes a segfault in the TIO interpreter.

This shouldn't violate rule 6, because any competent Underload interpreter would do TCO.
> 1 votes

# Answer
## REXX, 14 bytes

```
do i=0
  i=j
  end

```

This creates an infinite for-loop with `i` as a counter, but during the loop, `i` is reassigned from `0` to `j`, which, as an unassigned symbol, contains the string `J`.

The result:

```
     1 +++ do i=0
Error 41 running "test.rexx", line 1: Bad arithmetic conversion
[Finished in 0.1s with exit code 215]

```

Another option is to `drop i`, but that is three bytes longer.
> 1 votes

# Answer
# Whitespace, 16 bytes

```
[S S S N
_Push_0][N
S S N
_Create_Label_LOOP][T   N
S T _Print_top_as_integer][N
S N
N
_Jump_to_Label_LOOP]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

Probably my shortest Whitespace answer thus far. :)

**Explanation in pseudo-code:**

```
Push 0 to the top of the stack
Start LOOP:
  Pop and print the top of the stack as integer to STDOUT
  Go to next iteration of LOOP

```

**Run process**

```
Command    Explanation             Stack    STDOUT    STDERR

SSSN       Push 0                  [0]
NSSN       Create Label_LOOP       [0]
 TNST      Print top as integer    []       0
 NSNN      Jump to Label_LOOP      []

 TNST      Print top as integer    []                 Error: Can't do OutputNum

```

Stops with an error because it tries to output the top of the stack, which isn't there anymore.
> 1 votes

# Answer
# HadesLang, 34 bytes

```
func o[]
while[true]
o: //Recursive call to o
end
end
o: //Call o the first time

```

This just calls itself infinitely, resulting in a `System.StackOverflowException`after ~300ms.
> 1 votes

# Answer
# Zsh, 18 bytes

Abusing the short form of the `for` and implicit short command list. Will report "Command not found" for the first iteration, but will continue to the second and then crash.

```
for i (1 0) $[i/i]

```

Try it online!

EDIT: Boringly, `for i (- exit) $i` is one character shorter.
> 1 votes

# Answer
# Julia 1.0, 12 bytes

```
[1,-1].|>√

```

This broadcasts (`.|>` the pipe operator with the `.` annotation for broadcast) the square root function  over the vector `[1,-1]`.  throws a `DomainError` for negative values of `Real` types (like `Int`), so this fails on the second iteration. Roughly equivalent to `[√x for x in [1,-1]]`.

The fact that √ throws a DomainError for negative values of Real types happens to be a classic example of the design choices that allow Julia to act in many ways like a dynamic language (eg matlab, python) but generally compile to match the speed of fully typed languages (eg c, FORTRAN). It's discussed here in the Julia manual.

Try it online!
> 1 votes

# Answer
# Java, 26 bytes

Runs out of memory after around 2-3 seconds on TIO (exactly 27 iterations)

```
v->{for(var a=".";;a+=a);}

```
> 1 votes

# Answer
## Keg, ~~5~~ 4 bytes

```
1{_}

```

After popping 1 from the stack using an infinite loop, it tries to pop from the empty stack, which terminates the loop.
> 1 votes

# Answer
# BrainFuck (4 bytes)

`+[+]` This will just increment the number in the current pointer until it goes over the maximum allowed size
> 0 votes

# Answer
```
for i in [1]:
    print i

```

python code, not sure if this counts because it is ending not erring

```
for(var i in millis()){for(var j in millis()){for(var k in millis())for(var l in millis())println(i*j*k*l)}}}}

```

much longer

JavaScript code, will give a runtime error because it is running a ton of code each frame
> 0 votes

# Answer
# QC 3 bytes

`$01`

The program jumps into code at address 1, where it encounters 0, which expects 2 bytes after it, not 1. Because of that, it crashes with unexpected end of code message.

To try this code you need compile the interpreter yourself
> 0 votes

# Answer
# Bean, 4 bytes (non-competing)

```
5¥:(

```

Assembles to the JavaScript:

```
while(1);

```

Try the demo here! Running in a modern browser, this typically prompts the user within 30 seconds with a message saying

> The following page(s) have become unresponsive. You can wait for them to become responsive or kill them.
> 0 votes

# Answer
# Javscript (ES6), ~~12~~ 16 bytes

`(a=i=>a())() // Old code, not valid`

`(a=i=>i?a():z)```

This produces the error: `Uncaught ReferenceError: z is not defined`
> 0 votes

# Answer
# k, 4 chars

```
,:\0

```

Will terminate after a few seconds with `SEGV`
> 0 votes

# Answer
# C

## prints a - z using only 1 for loop

## (which is readable, hopefully)

```
for(int i='a';i<='z';printf("%d\n",i),i++);

```

### Edit: shortened even more: putchar() instead of printf

```
for(int i='a';i<='z';putchar(i),i++);

```

## working program:

```
#include <stdio.h>
int main() {
  for(int i='a';i<='z';putchar(i),i++);
  return 0;
}

```
> 0 votes

# Answer
# Python 3, ~~33~~ 16 Bytes

New code:

```
for i in 1,0:0/i

```

I realises just after posting this that a division by 1 then 0 would produce an acceptable answer, allowing me to shrink my code by more than 50%

Old code:

```
for i in 0,1:
 if i:raise IOError

```
> -2 votes

---
Tags: code-golf
---


title: A Portuguese sequence of integers

text:
# Question
Title: A Portuguese sequence of integers
# Context

Consider the following sequence of integers:

$$2, 10, 12, 16, 17, 18, 19, ...$$

Can you guess the next term? Well, it is \\$200\\$. What about the next? It is \\$201\\$... In case it hasn't become obvious to you, this is the sequence of positive integers whose name starts with a letter `D` in Portuguese.

# Task

Given a positive integer \\$n\\$, decide if it belongs in the sequence or not. An algorithm to do so is given next to the Output section.

# Input

A positive integer \\$n\\$, no greater than \\$999999999\\$.

# Output

A truthy/falsey value, representing whether or not the input belongs in the sequence. Truthy if it does, falsey if it doesn't. Truthy/falsey can't be switched for this challenge.

For \\$0 \< n \< 10^9\\$, here's how to determine if \\$n\\$ is part of the sequence. If \\$9 \< n\\$, say \\$ab\\$ are its two leading digits, so that if \\$n = 583\\$, \\$a = 5\\$ and \\$b = 8\\$. If \\$n \< 10\\$ then \\$a = n\\$. Let \\$k\\$ be the number of digits of \\$n\\$, so that if \\$n = 583\\$, \\$k = 3\\$. \\$n\\$ is in the sequence if any of these hold:

* \\$a = 2\\$ and \\$k = 1, 3, 4, 6, 7, 9\\$;
* \\$ab = 10, 12, 16, 17, 18, 19\\$ and \\$k = 2, 5, 8\\$

Please notice that standard loopholes are forbidden by default, in particular trivialising the challenge by using a language with a trivial numeric type.

(The rules above generalise trivially for \\$n\\$ arbitrarily big but I capped the input for simplicity)

# Test cases

## Truthy

```
2
10
12
16
17
18
19
200
201
223
256
10000
10100
10456
10999
12000
12180
12220
16550
17990
18760
19000
200000
212231
256909
299999
10000000
10999999
12000000
12999999
16000000
16562345
16999999
17000000
17999999
18000000
18999999
19000000
19999999
200000000
200145235
200999999
201000000
245345153
299999999

```

## Falsy

```
1
3
4
5
6
7
8
9
11
13
14
15
20
100
1000
1200
1600
1738
1854
1953
20000
21352
120000
160000
170000
180000
190000
20000000
100000000
120000000
160000000
170000000
180000000
190000000
999999999

```

---

This is so shortest submission in bytes, wins! If you liked this challenge, consider upvoting it! If you dislike this challenge, please give me your feedback. Happy golfing!

# Answer
> 35 votes
# Wolfram Language (Mathematica), 42 bytes

Of course there is a built-in for this...
And as @Charlie mentioned we can golf `"Portuguese"` to `"Spanish"` and save 3 bytes

```
#~IntegerName~"Spanish"~StringTake~1=="d"&

```

Try all test cases

-13 bytes from @att

# Answer
> 11 votes
# perl -plF, 55 41 bytes

Using ideas from @Dom Hastings, and eliminating common expressions:

```
$x=@F=~/[258]/;$_=/^2/&!$x|/^1[026-9]/&$x

```

Try it online!

## How does it work?

Due to the `-F` option, the input is split on characters which are put in the array `@F`. So, if we use `@F` in scalar context, we have the length of the number.

First, we set `$x` to true if the number contains 2, 5, or 8 digits (it's given the number is at most 9 digits).

The rest is straightforward. We check whether the number starts with `2`, and does not contain 2, 5, or 8 digits, or whether it starts with `10`, `12`, `16`, `17`, `18`, or `19`, and contains 2, 5 or 8 digits.

# Answer
> 9 votes
# Python 2, 48 bytes

```
lambda n:988164-2**200>>n/1000**(len(`n/3`)/3)&1

```

Try it online!

**Python 2, 50 bytes**

```
f=lambda n:f(n/1000)if n>299else 988164>>n&1|n/200

```

Try it online!

An arithmetic solution. Chomps down `n` to a three-digit number by repeatedly removing the last 3 digits. Then, checks that the remaining three-digit number is one of `[2,10,12,16,17,18,19]`, or is between 200 and 299.

The `[2,10,12,16,17,18,19]` is checked against the set bits of a binary number, `988164`.

The `200≤n<300` check is simplified by making the `≥300` case never happen. We keep chomping groups of 3 digits if the number is at least 300 (rather than at least 1000), making the 300-999 case go to 0. This leaves us with a `200≤n` check that we do simply as `n/200`.

You might wonder why the `if/else` isn't shortened to `and/or` as usual, but the output potentially being truthy or falsey doesn't play nicely here.

**53 bytes**

```
import re
re.compile("(2|1[026-9]|2..)(...)*$").match

```

Try it online!

Porting Neil's Retina solution. Takes input as a string. Thanks to n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ for saving a byte and Sisyphus for saving two.

# Answer
> 7 votes
# 05AB1E, ~~25~~ ~~21~~ ~~20~~ ~~19~~ 18 bytes

```
2Ž Ć.¥T+ªƵžIgåèÅ?à

```

-1 byte thanks to *@ovs* and -1 byte after being inspired by *@ovs* in the comments

Try it online or verify all test cases.

**Explanation:**

```
2                   # Push a 2
 Ž Ć                # Push compressed integer 24111
    .¥              # Push the cumulative sum of its digits with 0 prepended:
                    #  [0,2,6,7,8,9]
      T+            # Add 10 to each: [10,12,16,17,18,19]
        ª           # Append it to the 2: [2,[10,12,16,17,18,19]]
         Ƶž         # Push compressed integer 258
           Ig       # Push the input, and pop and push its length
             å      # Check that this length is in 258 (1 if truthy; 0 if falsey)
              è     # Use that to 0-based index into the list [2,[10,12,16,17,18,19]]
                    # ([10,12,16,17,18,19] if truthy; 2 if falsey)
               Å?   # Check whether the (implicit) input starts with any of these
                    # values (or the 2)
                 à  # And pop and push the maximum of the top item,
                    # which is either already 1 or 0 if it was 2,
                    # or the maximum of the list of truthy/falsey values if not
                    # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (sections *How to compress large integers?*) to understand why `Ž Ć` is `24111` and `Ƶž` is `258`.

# Answer
> 4 votes
# , ~~57~~ 56 bytes

```
substr(n<-scan(),1,2^!nchar(n)%%3<2)%in%c(2,10,12,16:19)

```

Try it online!

Note that `2^!nchar(n)%%3<2` is equal to `2` when `nchar(n)%%3==2`, and equal to `1` otherwise.

Extract either the first, or the first 2, digits of `n` (depending on the value of `nchar(n)%%3`), and check whether the result is in `c(2,10,12,16,17,18,19)`.

Works for arbitrarily large input.

# Answer
> 3 votes
# Ruby \+ `i18n` \+ `numbers_and_words`, ~~96 93~~ 91 bytes

```
require'i18n'
require'numbers_and_words'
I18n.with_locale(:pt){p gets.to_i.to_words[0]==?d}

```

Try it on repl.it!

It's probably longer than a simple pattern matching solution, but I wanted to try it anyway.

-3 bytes from ovs.

-2 bytes from Dingus.

# Answer
> 3 votes
# JavaScript (ES6),  ~~51 47~~  46 bytes

```
n=>(730>>n.length^n[0])&/^2|^1[^1345]/.test(n)

```

Try it online!

### How?

\\$730\\$ is the bit-mask of valid lengths when the first digit of \\$n\\$ is \\$2\\$:

```
730 = 1011011010
      ^ ^^ ^^ ^
      9876543210

```

Once it's been right-shifted by the number of digits, we XOR it with the first digit of \\$n\\$. Therefore, the least significant bit is left unchanged if the first digit is \\$2\\$ and inverted if the first digit is \\$1\\$. For other leading digits, we don't care about the result because the regex will not match anything anyway.

We either keep the least significant bit or discard it according to the result of the following regex:

```
/^2|^1[^1345]/
 ^2             // either a leading "2"
   |            // or
    ^1          // a leading "1" followed by ...
      [^1345]   // ... anything but 1, 3, 4 or 5

```

# Answer
> 3 votes
# Retina 0.8.2, 24 bytes

```
^(2|1[026-9]|2..)(...)*$

```

Try it online! Link includes test cases. Explanation: The rules simplify to: Take the first base 1000 digit, which should be either 2, 10, 12, 16-9, or 200-299.

# Answer
> 3 votes
# Charcoal, 22 bytes

```
¬⎇﹪⊕Ｌθ³⌕θ2⬤026789⌕θ⁺1ι

```

Try it online! Link is to verbose version of code. Explanation: Works by testing whether the string begins with either 2 or one of 10, 12, 16, 17, 18, or 19, depending on the number of digits in the string; Find() will return 0 if it does, which we then invert to provide the desired truthy answer. (And because we're working in negative logic, we actually use All() to see if any of the strings is found at position 0.)

```
     θ                  Input as a string
    Ｌ                   Length
   ⊕                    Incremented
  ﹪   ³                 Modulo literal `3`
 ⎇                      If nonzero then
       ⌕                Index of
         2              Literal string `2`
        θ               In input
          ⬤             Else map over characters
           026789       Literal string
                 ⌕      Index of
                    1   Literal string `1`
                   ⁺    Concatenated with
                     ι  Current character
                  θ     In input
¬                       (Any) zero

```

# Answer
> 3 votes
# Haskell, 52 bytes

```
(%)=div
f n|n>299=f$n%1000|r<-2^n=odd$n%200+988164%r

```

Try it online!

This is a translation of xnor's Python solution. They contributed a byte-save with `r<-2^n`, too!

# Answer
> 3 votes
# Jelly,  ~~18~~  16 bytes

-2 thanks to Sisyphus!

```
bȷḢbȷ2Ḣe“,-n’DÄ¤

```

**Try it online!** Or see the test-suite.

### How?

```
bȷḢbȷ2Ḣe“,-n’DÄ¤ - Link: n
 ȷ               - 1000
b                - (n) base (1000)
  Ḣ              - head -> x
    ȷ2           - 100
   b             - (x) base (100)
      Ḣ          - head
               ¤ - nilad followed by link(s) as a nilad:
        “,-n’    -   2824111
             D   -   digits
              Ä  -   cumulative sums -> [2,10,12,16,17,18,19]
       e         - exists in?

```

# Answer
> 3 votes
# Zsh, 37 bytes

```
>$#1$1
: (12|[34679]2|[258]1[^1345])*

```

Try it online!

Outputs via status code (`0` = is in sequence, `1` = is not in sequence).

Explanation:

* `>` \- create the file
    + `$#1` \- the length of the input
    + `$1` \- followed by the input itself
* `(12|[34679]2|[258]1[^1345])*` \- try to find a file matching this pattern:
    + `(||)` \- one of:
        - `12` (the literal input `2` which is of length `1`)
        - `[34679]2` \- any character from the set `34679`, then a `2`
        - `[258]1[^1345]` \- any character from the set `258`, then a `1`, then any character except one from `1345` (shorter than `026789`)
    + `*` \- followed by any string
    + this will produce an error if there is no file
* `:` \- and then do nothing with that file (this is required because otherwise `()` would be treated as a sub-shell)

# Answer
> 2 votes
# Scala, ~~98~~ 79 bytes

```
n=>{val m=n+"";if(m.size%3>1)Set(0,2,6,7,8,9)(m.take(2).toInt-10)else m(0)==50}

```

Try it online!

* Thanks to user for -19!!!!

# Answer
> 1 votes
# , ~~87~~ ~~82~~ 79 bytes

(or 82 bytes as a function)

```
`if`(36%%((k=nchar(n<-scan())-1)+5),n%/%10^k==2,n%/%10^(k-1)%in%c(10,12,16:19))

```

Try it online!

# Answer
> 1 votes
# Husk, ~~41 33~~ 42 bytes

```
§|§&ȯ€B19 26441084r↑2o₁L§&o='2←ȯ¬₁Ls
€d258

```

Try it online!

-8 bytes from Dominic Van Essen.

+9 bytes after corrections.

# Answer
> 1 votes
# Husk, ~~28~~ ~~26~~ ~~25~~ ~~23~~ ~~21~~ 20 bytes

or **19 bytes** by accepting input as a string

*Edit: -2 bytes thanks to LegionMammal978, then -1 more byte thanks to Zgarb*

```
€∫d2824111d↑d¹→=2%3L

```

Try it online! (header in TIO link loops over integers from 1 to 500, and outputs those beginning with 'D' in Portugese)

Port of Robin Ryder's R answer. Outputs zero (falsy) for numbers not beginning with 'D' in Portugese, or a positive integer (truthy) for numbers beginning with 'D'.

**How?**

```
€∫d2824111d`↑d¹→=2%3Ld
€                               # does the argument belong to this list:
 ∫                              # cumulative sum of
  d2824111                      # base-10 digits of 2824111
                                # (2,10,12,16,17,18 and 19)
          d                 # argument is the base-10 number formed from
           `↑d¹             # the first x digits of the input
                                # where x is calculated as:
               →=2%3Ld
               →                # 1 plus
                    Ld          # the number of input digits
                  %3            # mod 3
                =2              # equals 2?

```

# Answer
> 1 votes
# Ruby, ~~48~~ ~~47~~ 34 bytes

```
->s{s=~/^(2|1[026-9]|2..)(...)*$/}

```

Try it online!

Takes input is a string.

Based on ~~Abigail's Perl solution~~. Based on Neil's impressive regex.

---
Tags: code-golf, math, decision-problem, integer, natural-language
---