[Question]
  [
A **truth-machine** (credits goes to [this guy](https://esolangs.org/wiki/User:Keymaker) for coming up with it) is a very simple program designed to demonstrate the I/O and control flow of a language. Here's what a truth-machine does:
* Gets a number (either 0 or 1) from STDIN.
* If that number is 0, print out 0 and terminate.
* If that number is 1, print out 1 forever.
# Challenge
Write a truth-machine as described above in your language of choice. The truth-machine must be a full program that follows these rules:
* take input from STDIN or an acceptable alternative
	+ If your language cannot take input from STDIN, it may take input from a hardcoded variable or suitable equivalent in the program
* must output to STDOUT or an acceptable alternative
	+ If your language is incapable of outputting the characters `0` or `1`, byte or unary I/O is acceptable.
* when the input is `1`, it must continually print `1`s and only stop if the program is killed or runs out of memory
* the output must only be either a `0` followed by either one or no newline or space, or infinite `1`s with each `1` followed by either one or no newline or space. No other output can be generated, except constant output of your language's interpreter that cannot be suppressed (such as a greeting, ANSI color codes or indentation). Your usage of newlines or spaces must be consistent: for example, if you choose to output `1` with a newline after it all `1`s must have a newline after them.
* if and only if your language cannot possibly terminate on an input of `0` it is acceptable for the code to enter an infinite loop in which nothing is outputted.
Since this is a catalog, languages created after this challenge are allowed to compete. Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. Other than that, all the standard rules of [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") must be obeyed. Submissions in most languages will be scored in bytes in an appropriate preexisting encoding (usually UTF-8).
# Catalog
The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
## Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
## Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
## Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the snippet:
```
## [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
```
<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 320px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><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="language-list"> <h2>Shortest Solution 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> <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> <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><script>var QUESTION_ID = 62732; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 12012; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>
```
  
[Answer]
# [Hexagony](https://github.com/mbuettner/hexagony), 6 bytes
This was surprisingly tricky, ~~and I'm not convinced it's optimal...~~
```
<.@!$?
```
After padding and unfolding the code, this represents the following hex grid:
[![enter image description here](https://i.stack.imgur.com/6Q3Y4.png)](https://i.stack.imgur.com/6Q3Y4.png)
This uses a similar control flow [like my recent error-free cat program](https://codegolf.stackexchange.com/a/62306/8478), moving along anti-diagonals. To achieve that we start by deflecting the instruction pointer (IP) to the left, where the purple path wraps around to the lower left corner.
`?` reads the input as an integer. `!` prints it back. `.` is just a no-op. Now the corner of the grid acts as a branch:
If the input was `0`, the IP will continue along the red path, which simply terminates the program with `@`.
If the input was `1`, the IP will continue on the green path. Again, `.` is just a no-op, but `$` is the equivalent of Befunge's trampoline: it skips the next instruction. After wrapping, the next instruction would be the `?`, but due to `$` execution actually continues on the blue path, starting with `!` to print another copy of the `1`. This loop which only contains `!..$` is now repeated indefinitely.
### A study of control flow in Hexagony...
I believe the above solution is optimal. I've written a brute forcer, which checks all 6-byte Hexagony programs, which contain at least one each of `?!@` (which are necessary; I've also checked `:` and `%` in place of `@` to terminate with a division-by-zero error, but that didn't help either). The check prints all the programs which a) produce a `0` on input `0` and terminate and b) produce at least two `1`s (and nothing else) and *don't* terminate within the first 60 ticks of the program (200 ticks for 5-byte solutions). I doubt that any valid solution would take more than 200 ticks to correctly print the first `0` or the second `1` on such a small grid, so I don't think I've missed out on any potential solutions.
The search didn't yield any results for 5 bytes, but 57 results for 6 bytes (using `@`; there's no need to terminate with an error if we can solve this cleanly in the same amount of bytes). Of those 57 only 6 were false positives which actually printed only two `1`s and then entered an infinite loop without printing any more. One solution was listed twice because it contained two `!` commands. That leaves exactly 50 valid solutions.
There is a certain amount of degeneracy between the solutions where one or two characters are not substantial, e.g. because they're effectively no-ops anyway. The solutions can be grouped into 23 sets of genuinely distinct programs (in some cases, there is only a single character difference between two sets, but it changes the control flow substantially, so I've counted them separately). Two of the groups even make use of multiple instruction pointers in a very unexpected way. As I would never have come up with most of these ways to use the branches and mirrors, they make a very interesting study of what sorts of control flow are possible in Hexagony, and I have definitely learned some new tricks for future golfs.
The *overall* control flow is almost always the same: read a number, print it. If it's `0` find a way to the `@`, if not keep looping through the `!` while mainting an edge value of `1`. There are four notable exceptions:
* One solution (the one with two `!`) prints two `1`s per iteration through the grid, therefore printing about twice as fast as the majority of programs. I've marked this one with `x2` below.
* A few solutions (those which contain an `o`) replace the `1` with a `111` (the character code of `o`), so they print *three* `1`s per iteration, making them print about three times as fast as the majority of programs. I've marked these with `x3` below.
* Two solutions *append* a `1` to the edge value in each iteration (so `1` --> `11` --> `111` --> ...). Those print *very* fast, but they'll run out of memory eventually. I've marked these with `OoM` below.
* Two solutions enter a very tight loop which merely bounces back and forth over the `!`, printing on every other tick (instead of of every 5th or so), which makes them slightly faster (and neater). I've marked these with `><` below.
So here is the entire zoo:
```
#1                #5                #12                #19
?!/$.@            ?$!>$@            .?!/$@             |!|?$@  # ><
?!/$1@  # OoM     ?$!|$@            =?!/$@
?!/$=@                                                 #20
?!/$\@            #6                #13                $@.?<!
?!/$o@  # x3      ?/!<|@            .?/!$@             $@1?<!  # OoM
?!/$!@  # x2                        =?/!$@             $@=?<!
                  #7                                   $@o?<!  # x3
#2                ?\!<|@            #14
?!>$)@                              \!?__@             #21
?!>$1@            #8                                   _>_!?@
?!>$o@  # x3      ?<!>$@  # ><      #15
?!|$)@                              \_?!$@             #22
?!|$1@            #9                                   <!@.$?
?!|$o@  # x3      ?\$!@$            #16                <!@/$?
                                    \_?!_@             <!@=$?
#3                #10                                  <$@!$?
?!|)$@            ?~#!@)            #17                <.@!$?
?!|1$@            ?~#!@1            $$?\@!             </@!$?
?!|o$@  # x3                                           <=@!$?
                  #11               #18
#4                ?$)\@!            \$?\@!             #23
?_!<@>            ?$1\@!                               <<@]!?
                  ?$o\@!  # x3
```
The following is a short walkthrough for a handful of the more representative groups. Especially groups 10 and 23 are worth checking out. There are many other interesting and sometimes convoluted paths in the other groups, but I think I've bored you enough at the end of this. For anyone who really wants to learn Hexagony, these are definitely worth investigating though, as they exhibit even more possible uses of the mirrors and `$`.
**Group 1**
This one isn't much more elaborate than my original solution, but the paths go in different directions. It also allows for the largest number of variations in a single cell, as the right-most no-op can be replaced with 5 different commands which still make this valid without changing the structure:
[![enter image description here](https://i.stack.imgur.com/Tm3rR.png)](https://i.stack.imgur.com/Tm3rR.png)
**Group 2**
This one is quite interesting, because it only moves horizontally. After wrapping to the `>`, the IP reverses immediately, taking the branch in the corner. It's not entirely well visibly no the diagram, but in the case of the `1` we traverse the first row again, but backwards this time. This also means we run into `?` again, which now returns `0` (EOF). This is fixed with `)` (increment) to keep printing `1`s. This also has 5 variations, as `)` could also be `1` or `o`, and `>` could also be `|`:
[![enter image description here](https://i.stack.imgur.com/0szdq.png)](https://i.stack.imgur.com/0szdq.png)
**Group 3**
This one looks almost identical to the previous one but it's messy as hell. Up to hitting `|` and then traversing the bottom or top row it's the same. But in the case of a loop, the `$` now skips over the `)` *onto* the mirror. So we follow the turquoise path to the right, now hit the increment, skip over the `@` before we wrap around to the `|` *again* and *then* go back to the green path at the top.
[![enter image description here](https://i.stack.imgur.com/tY4Up.png)](https://i.stack.imgur.com/tY4Up.png)
**Group 4**
I thought this one was particularly nifty:
[![enter image description here](https://i.stack.imgur.com/MlEZV.png)](https://i.stack.imgur.com/MlEZV.png)
The `_` mirror in the top right corner is initially a no-op, so we print with `!` and hit the `<`. The `0` path now hits the horizontal mirror and terminates. The `1` path takes a really interesting trajectory though: it deflects down, wraps to the `!`, gets redirected towards the horizontal and then wraps back to the `!` *again*. It then keeps moving in this rhombus shape, printing twice per iteration (every third tick).
**Group 8**
This is one of the two solutions with a really tight printing loop:
[![enter image description here](https://i.stack.imgur.com/C5egM.png)](https://i.stack.imgur.com/C5egM.png)
The `<` acts as the branch. After wrapping twice, `0` hits `@`. `1` on the other hand, first skips the `?`, then `>` sends it onto the the `$` again, so that is skips the `@`. Then the IP wraps into the turquoise path, where it bounces back and forth between the `>` and `<` (wrapping around the edge in between).
**Group 10**
One of two groups which use other instruction pointers, and it's absolutely beautiful. Hexagony has 6 - each one starts from a different corner along the clockwise edge, but only one of them is active at a time.
[![enter image description here](https://i.stack.imgur.com/j7ZeZ.png)](https://i.stack.imgur.com/j7ZeZ.png)
As usual, we read with `?`. Now `~` is unary negation: it turns the `1` into a `-1`. Next, we hit the `#`. This is one way to switch between IPs: it takes the current edge value modulo 6 and switches to the corresponding IP (IPs are numbered from `0` in the clockwise direction). So if the input was `0`, then the IP simply remains the same, and travels boringly straight ahead into `!@`. But if the input was `1`, then the current value is `-1` which is `5 (mod 6)`. So we switch to the IP which starts on the very same cell (the green path). Now `#` is a no-op and `?` sets the memory edge to `0`. `)` increments so `!` prints a `1`. Now we hit `~` again to ensure that `#` is still a no-op (as opposed to switching us to IP 1 which would terminate the program). It's mindblowing how well everything fits together in this little program.
**Group 22**
Just to note, this is the group my original solution is in. It also happens to be largest group, because the no-op can be in two different places, and there are several choices for the actual (effective no-op) command.
**Group 23**
This is the other group using multiple IPs. In fact this one uses *3* different IPs. The top right corner is a bit of a mess, but I'll try to walk you through this:
[![enter image description here](https://i.stack.imgur.com/LxAc6.png)](https://i.stack.imgur.com/LxAc6.png)
So, the beginning you've seen before: `<` deflects North-East, `?` reads input. Now `]` is another way to change between IPs: it hands control to the next IP in clockwise order. So we switch control to the turquoise path which (I know it's hard to see) starts in the North-East corner going South-East. It is immediately reflected by the `<` so that it wraps to the South-East corner, going North-West. It *also* hits the `]` so we switch to the *next* IP. This is the grey path starting in the East corner, going South-West. It prints the input, then wraps to the North-East corner. `<` deflects the path into the horizontal, where it is reflected by the *other* `<`. Now the right-hand `<` acts as a branch: if the input was `0`, the IP moves North-East, and wraps to the `@`. If the input was `1`, the IP moves to the `!`, wraps to the lef-thand `<` where it is reflected... now in the corner, it wraps back to the `!`, gets deflected by the the right `<`, reflected by the left `<` and the paths starts over...
Quite a mess, but a beautiful mess. :)
---
Diagrams generated with [Timwi's](https://codegolf.stackexchange.com/users/668/timwi) amazing [HexagonyColorer](https://github.com/Timwi/HexagonyColorer).
[Answer]
# [Motorola MC14500B](https://en.wikipedia.org/wiki/Motorola_MC14500B) Machine Code, 2 bytes
In hex:
```
58EC
```
Explanation:
```
5  OR the register with input from the data bus
8  Write the register to the data bus
E  Skip next instruction if register is zero
C  Jump
```
The Motorola MC14500B is a 1-bit microcontroller; it has one 1-bit register and a 1-bit data bus. Since the opcodes are 4 bits each, there are only sixteen; half of them carry out a logical operation between the register and the bit on the data bus.
The jump instruction sets a jump flag; when no address is provided, it is common to set the program counter to 0. If the input bit was zero, the processor will not jump. If the input bit was 1, the processor jumps back to the start; since we're `OR`ing with input, it doesn't matter what the input signal is afterwards—the register will then be 1 forever.
As is conventional, the register is initialized to 0.
A list of the opcodes can be found on the data sheet, or [here](https://www.brouhaha.com/%7Eeric/retrocomputing/motorola/mc14500b/).
[Answer]
## Arnold C, 296 Bytes
```
IT'S SHOWTIME
    HEY CHRISTMAS TREE i    
    YOU SET US UP @NO PROBLEMO
    BECAUSE I'M GOING TO SAY PLEASE i
        STICK AROUND i
            TALK TO THE HAND i
        CHILL
    BULLSHIT
        TALK TO THE HAND i
    YOU HAVE NO RESPECT FOR LOGIC
YOU HAVE BEEN TERMINATED
```
Not really competitive, but for the fun of it.
Does not support stdin, replace `@NO PROBLEMO` with `@I LIED` for a zero value. `@No Problemo` is 1.
Run with (assuming file is truthmachine.arnoldc):
```
wget http://lhartikk.github.io/ArnoldC.jar
java -jar ArnoldC.jar truthmachine.arnoldc
java truthmachine
```
[Answer]
# Minecraft, 18 Bytes (MC Version 15w45a)
[![minecraft sketch](https://i.stack.imgur.com/A5eP4.png)](https://i.stack.imgur.com/A5eP4.png)
As you can see, there is a lever directed into the repeating command block, which has the command `say 1` in it. There is an signal inverting torch on top of that, which directs power into the single-run command block with the command `say 0` in it.
Whenever the switch is directed towards truthy, the repeater block uses the code `say 1` to output infinite `1`s. When the lever is redirected to false, it outputs a single `0`.
Note that this outputs a `[@]` by default. If you *really* want just straight up 1s and zeros, this becomes 34 bytes, where the code in the command blocks are `tellraw @a [1]` and `tellraw @a [0]`. This is using @Cᴏɴᴏʀ O'Bʀɪᴇɴ's suggested byte count for MC [as can be found in Meta](https://codegolf.meta.stackexchange.com/a/7397/44713).
[Answer]
# Bash + GNU utils, 13
```
grep 0||yes 1
```
---
# Bash, 35
```
read n;for((;n;));{ echo 1;};echo 0
```
[Answer]
# Microscript, 3 bytes
```
i{p
```
The shortest one I know.
Explanation:
```
i  Takes numeric input and puts it in register 1
{  while register 1 is truthy
  p  Print the contents of register 1
```
Microscript has implicit printing of register 1 upon termination, which is the reason why an input of `0` gets printed once.
[Answer]
# Ruby, 20
```
print while/1/||gets
```
Run from the command line to avoid warnings, as
```
ruby -e "print while/1/||gets" <<< 0
ruby -e "print while/1/||gets" <<< 1
```
Explanation:
Less golfed, this is
```
while /1/ || gets
  print
end
```
When a Regexp is used in a conditional, it evaluates as falsey unless the variable `$_` is populated and matches the pattern. On the first time through the loop, `$_` is empty so we fall through to `gets`, which sets the value of `$_` to a line read from STDIN. `print` with no arguments prints `$_`. Now we evaluate the conditional again. If we read in 1, we short-circuit and just print 1 again, and so on forever. Otherwise, we fall through to `gets`, but since there's no second line of input, `gets` returns nil, so the loop ends.
[Answer]
# Turing Machine Code, ~~32~~ 22 bytes
Using the rule table syntax found [here.](http://morphett.info/turing/turing.html)
```
0 0 0 * halt
0 * 1 r 0
```
[Answer]
## Python 2, 29 bytes
```
a=input()
while 1:print a;1/a
```
This terminates with a division error on `0`, which is [allowed by default](https://codegolf.meta.stackexchange.com/a/4781/20260).
[Answer]
# JavaScript, 28 bytes
[For loops are often shorter than while loops.](https://codegolf.stackexchange.com/a/2695/45393)
`alert(x)` returns `undefined`, which is falsy, so the bitwise or operator, `|`, casts it to `0`. Thus, if `x` is `"0"`, alert once, otherwise keep looping. Uses `alert` for STDOUT like [this answer](https://codegolf.stackexchange.com/a/62742/45393).
```
for(x=prompt();alert(x)|x;);
```
[Answer]
# Brainfuck, ~~41~~ ~~36~~ ~~31~~ 30 bytes
Shortened by printing once right after input and with help from Ethan and user46915.
```
,.+++[->>+<-----<]>>---<-[>.<]
```
Previous version: Subtract 48 from the input, and if it's not zero, add 1 to the 48 to print ASCII `1` forever, otherwise print `0`.
```
-[>+<-----]>--->,<[->->+<<]>[>+<]>.<[>.<]
```
I ran it [**here**](http://esoteric.sange.fi/brainfuck/impl/interp/i.html), but due to buffered output, you cannot see any output since the program never terminates on `1`.
Edit: I had forgotten to print `0` on input `0`. Fixed now. I like the `>.<` faces at the end.
[Answer]
# Pyth, ~~4~~ ~~3~~ 2
```
Wp
```
There is ~~a~~ no! trailing space (thanks isaac :) ). The space used to be required to make the while loop compile, but Pyth has since been updated. Normally that would disqualify using it, but since this is a catalog it should be valid.
### Explanation:
```
Wp        : implicit Q = eval(input)
W         : while
 p        : print and return the value of Q, to be evaluated as the while condition
          : Functions without enough arguments automatically use Q now
          : do nothing in the body of the while loop
```
[Answer]
# Piet, 27 18 16 codels
(Codel is a fancy name for pixel used to avoid confusion when an image is stretched for viewing. I counted codels instead of bytes because piet scripts are saved as images, so the physical size may vary. I think an ideal file format that would save this piet as efficiently as possible would take 11 bytes. In practice, my tiny gif file is 62 bytes, with optimal palette data. Tell me if I should use this as the size of my entry instead of the codel amount.)
Original image: [![tiny version](https://i.stack.imgur.com/R9SOq.gif)](https://i.stack.imgur.com/R9SOq.gif)
Enlarged: [![enlarged version](https://i.stack.imgur.com/5T9WW.png)](https://i.stack.imgur.com/5T9WW.png)
In piet, the difference between two colors is what determines which command runs, so seeing the same color twice doesn't mean it does the same action. The execution begins in the top-left codel. Then it moves horizontally, performing the following:
1. Read a number and put it on the stack
2. Duplicate the top of the stack
3. Pop and output the top of the stack
4. Pop the top of the stack and rotate clockwise that number of times.
If the input was 1, the cursor then moves down into the lime codel, which pushes 1 on the stack. Then the execution continues going left. When the cursor passes from a color to white and from white to a color, nothing happens. Since black is considered as walls too, the cursor ends up going back to the lime codel on the top line, and repeats the whole thing from step 2.
If, however, the input was 0, the cursor will never go down and will end up in the blue J on the right (pun intended, it was worth it), were it will stay trapped (because the top, right, left and bottom sides of this J-shaped block are next to black codels or the edge of the image). Since the cursor is trapped, execution ends.
**Unexpected values:**  
If the user writes another number, it will still be printed, then the cursor will rotate more or less times based on the value.
* Multiple of 4 or 0: execution continues horizontally and ends.
* Multiple of 3: Since going up is impossible, the cursor immediately rotates clockwise and continues horizontally, then ends.
* Multiple of 2 and not a multiple of 4: the cursor rotates and starts moving to the left. Luckily, all this does is perform a bunch of operations that don't affect the program flow and end up emptying the stack. When an operation can't be done because the stack is empty, it is simply ignored. When it hits the top left corner, the cursor has nowhere else to go but to the right again, effectively restarting the program.
* Other values: The cursor goes down as if it would with 1, which makes it print 1 forever. If the input is 5, the output will be `5111111111111...`
Any non-integer value will terminate the program. Execution will continue normally, but all operations will be ignored since there is nothing in the stack. So in a way, the program never crashes - it either stops normally or loops forever.
---
**PietDev friendly version**
PietDev (a very basic online Piet IDE) seems to have trouble with white codels so I made a new version which manually rotates back up instead of relying on proper white codel automatic rotation. And I didn't even need to use a new color! If you want to test with it, make sure you draw a black border around the code because PietDev doesn't support custom program sizes.
[![tiny version](https://i.stack.imgur.com/dSkIn.gif)](https://i.stack.imgur.com/dSkIn.gif)
[![enlarged version](https://i.stack.imgur.com/pP6qn.gif)](https://i.stack.imgur.com/pP6qn.gif)
---
**Older versions**
The first version didn't push 1 back on the stack and instead looped back to an earlier duplication instruction. It also had decorative useless codels.
[![Tiny pattern which is actually a piet code](https://i.stack.imgur.com/xGoGM.png)](https://i.stack.imgur.com/xGoGM.png)
[![Enlarged version](https://i.stack.imgur.com/50aw2.png)](https://i.stack.imgur.com/50aw2.png)
Then I had the idea to push 1 on the stack to remove the blank line. It's funny how I thought of it thanks to my decorative codels.
[![tiny version](https://i.stack.imgur.com/K8JeP.gif)](https://i.stack.imgur.com/K8JeP.gif)
[![large version](https://i.stack.imgur.com/N7l8K.gif)](https://i.stack.imgur.com/N7l8K.gif)
Then I realized I had an extraneous dup that wasn't needed anymore, and I reduced the number of colors to save up on palette data in the image. I also got rid of the single decorative codel because I don't know.
[Answer]
# [Chip](https://github.com/Phlarx/chip), 6 bytes
```
e*faAs
```
Chip is a 2D language that behaves a bit like an integrated circuit. It takes input, one byte at a time, and breaks out the bits to individual input elements. Output stitches the values of output elements back together into bytes.
Let's break this down:
`*` is a source signal, it will send a true value to all adjacent elements.
`e` and `f` correspond to the fifth and sixth bit of the output.
So, `e*f` produces binary `00110000`, which is ASCII char "0".
Now, `A` is the first bit of input and `a` is the first bit of output, so `aA` copies that bit from input to output. So, when combined with `e*f`, an input of ASCII "0" produces "0", and "1" produces "1". (There is no interaction between `f` and `a`, since neither produce any signal.)
The `s` on the end, when activated by a true signal, will prevent input from advancing to the next byte, meaning that the whole thing will run again with the same input.
Since the first byte of "0" is zero, it won't activate this element and the program will print "0", and thereby exhaust its input, which allows it to terminate. "1", however, activates this element, which means that "1" is output, but not consumed on the input, allowing the cycle to repeat indefinitely.
If values 0x0 and 0x1 are used for output, rather than ASCII, we can eliminate the `e*f` part, resulting in only **3 bytes**:
```
aAs
```
If the zero must terminate itself, rather than expecting stdin to close, we get the following, which inverts the first byte with `~`, and passes the result to `t`, which terminates the program (**10 bytes**):
```
aA~te*f
 s
```
(`t` also produces no signal, so there is no interaction between `t` and `e`.)
[Answer]
# [Brainbool](https://esolangs.org/wiki/Brainbool), 5 bytes
```
,.[.]
```
Brainbool is Brainfuck, but it only operates on bits, and does I/O through `0` and `1` characters.
[Answer]
# LOLCODE, 119 bytes
```
GIMMEH n
n R SUM OF n AN 0
BOTH SAEM n AN 0, O RLY?
YA RLY
 VISIBLE 0
NO WAI
 IM IN UR l
  VISIBLE 1
 IM OUTTA UR l
OIC
```
Ungolfed:
```
HAI
BTW, Read n as a string from STDIN and convert to an integer
GIMMEH n
n R SUM OF n AN 0
BTW, Test n for equality with 0
BOTH SAEM n AN 0, O RLY?
YA RLY
    BTW, Write 0 to STDOUT and exit
    VISIBLE 0
NO WAI
    BTW, Loop forever, printing 1
    IM IN YR l
        VISIBLE 1
    IM OUTTA YR l
OIC
KTHXBYE
```
[Answer]
# [Bitwise Cyclic Tag](http://esolangs.org/wiki/Bitwise_Cyclic_Tag), 3 bits or < 1 byte
Bitwise Cyclic Tag is one of the simplest Turing-complete languages out there. It works with two bitstrings, the *program* and the *data*. The bits of the *program* are read cyclically and interpreted as follows:
* `0`: Delete the first data bit (and output it, in implementations that have output).
* `1x`: If the first data bit is `1`, append `x` (representing either `0` or `1`) to the end of the data. (If the first data bit is `0`, do nothing.)
The program runs until the data string is empty.
### Truth-machine
```
110
```
When the data string is set to `0`:
* `11` does not append anything because the first data bit is not `1`.
* `0` deletes/outputs `0`.
* The data string is now empty and the program halts.
When the data string is set to `1`:
* `11` appends a `1`.
* `0` deletes/outputs `1`.
* The data string is back to a single `1` and the program is back to where it started, so we loop forever.
[Answer]
## [Labyrinth](https://esolangs.org/wiki/Labyrinth), 7 bytes
```
 ?+
@!:
```
Labyrinth is a 2D stack-based language where control flow depends on the sign of the top element of the stack, checked after every instruction. Execution begins moving rightward from the first valid instruction on the top row, which here is the `?`.
The relevant instructions are:
```
?      Input integer
+      Add top two elements (Labyrinth's stack has infinite 0s on the bottom)
:      Duplicate top element
!      Output as number
@      Terminate program
```
If the input is 0, the IP reads input with `?`, adds the top two of the stack (`0 + 0 = 0`), then duplicates `:` and outputs `!` a 0. Here we encounter the sole junction in the program, and have to check the top of the stack to determine where to go. Since the top is 0, we move forward and terminate with `@`.
On the other hand, if the input is 1, we do the same instruction as before (but outputting a 1) before reaching the junction at the `!`. Now the top of the stack is positive, causing us to turn right into the `?`. On EOF Labyrinth pushes 0, so we do `0 + 1 = 1` at the `+`, duplicate `:`, and output `!`. Once again we have a 1 at the top of the stack and the loop continues.
For a bonus, here's @MartinBüttner's 7 byte solution, which operates similarly:
```
?+!@
1!
```
Note that, unlike most languages, `1` actually pops `n` off the stack and pushes `n*10 + 1`, making the building up of large numbers easy. However, since the top of the stack is empty at that point, it's no different from merely pushing 1.
[Answer]
## C, 37 bytes
A different take on how to do it in C.
```
main(c){for(gets(&c);putchar(c)&1;);}
```
`c` defaults to an `int` of value 1. `gets(&c)` gets a string from `stdin`, here clobbering the value of `c`, hackishly since `c` is not a `char*`. `putchar(c)` prints the value of `c` to `stdout`, and returns `c`. Since `'0'` is 48 and `'1'` is 49 in ASCII, we can use the last bit (`&1`) to determine which it is. If it's `'0'`, the loop breaks. Otherwise, it goes forever.
Compiles (with a warning about `gets`) and runs under `gcc-4.8` on Linux.
[Answer]
## [><>](https://esolangs.org/wiki/Fish), 7 bytes
```
i2%:n:,
```
This uses the fact that ><> pushes -1 on EOF, which is 1 mod 2. It also uses divide by 0 for termination (which is apparently okay since the consensus is that STDERR output is ignored).
Just for reference, exiting cleanly without errors is an extra byte:
```
i2%:n?!;
```
[Answer]
# [><>](http://esolangs.org/wiki/Fish), 6 bytes
```
::n?!;
```
Pushes the input on the stack to start
```
:        copy top element on stack
 :       copy top element on stack again
  n      pop and outputs top element
   ?     condition trampoline - pops top element, if it is zero skips next instruction
    !    trampoline skips next instruction
     ;   finish execution
```
[Answer]
## APL, 6 bytes
```
→⎕←⍣⍲⎕
```
Explanation:
```
     ⎕ Read the input, then
 ⎕←    write it out
   ⍣   repeatedly
    ⍲  until NAND of it with itself becomes true.
→      Branch to zero to avoid printing the result again.
```
[Answer]
## [Seriously](https://github.com/Mego/Seriously/tree/v1), ~~4~~ 3 bytes
[Crossed-out 4 is still 4 :(](https://codegolf.stackexchange.com/questions/63755/rotate-the-anti-diagonals#comment153855_63756)
```
,W■
```
`,` reads a value from STDIN. `W` starts a loop that runs while the value on top of the stack is truthy, with the body `■`. `■` prints the top stack element without popping. The loop is implicitly closed at EOF.
On input of `0`, the loop never executes (since `0` is falsey), and the program ends at EOF, automatically popping and printing every value on the stack. On input of `1` (or any value that is not `0`, `""`, or `[]`), the loop runs infinitely.
In [Actually](https://github.com/Mego/Seriously), the leading `,` is not needed (thanks to implicit input), bringing the score down to 2 bytes.
[Answer]
# GNU sed, 10
```
:;/1/{p;b}
```
### Explanation
* `:` define an unnamed label
* `/1/` If input matches the regex `1`, then
* `p` print the pattern space (i.e. 1)
* `b` and jump back to the unnamed label (forever)
* If the input was not 1 (i.e. 0), then the pattern space is printed unmodified and the program ends.
[Answer]
## [Brian & Chuck](https://github.com/mbuettner/brian-chuck), 21 bytes
```
,}<-{-?<SOH>_{+?
_>+{?<.p
```
Here, `<SOH>` should be replaced with the corresponding control character (0x01).
### Explanation
The basic idea is to subtract the character code of the input (48 or 49) from the `p` at the end of Chuck, which will either give a `?` (which is a valid command) or a `@` which is a no-op.
`,` reads the input character into Chuck's first cell (marked with `_`). We want to decrement this value down to `0` in a loop, while making some other changes:
`}<` moves to the `p` and `-` decrements it. Then `{` moves back to the input cell `-` decrements that as well. As long as this isn't zero yet, `?` gives control to Chuck. Now `>` moves Brian's tape head one cell to the right (which is initialised to `1`) and `+` increments that. Then we reset the loop with `{?`.
By the time the first cell on Chuck hits `0`, the `<SOH>` cell will have been incremented to the character we've read from STDIN and `p` will be `?` for input `1` or `@` for input `0`.
Now `?` doesn't switch control any more. The `0` or `1` after it is a no-op, as is the null-byte (represented by `_`). `{` moves back to Chuck's first cell and `+` increments to ensure that it's positive, such that `?` hands control over to Chuck.
This time `>+` increments the cell after the end of Brian's initial tape. That cell is garbage but we'll never use it. Now `{` doesn't scan all the way to the front of Brian's tape, but only to the `_`. Hence `?` is a no-op because the current cell is zero. Then `<.` moves one to the left (the copy of the input character) and prints it.
Finally, we encounter the `?` or `@`. If the input was `0` and this cell is `@` it's a no-op and the program terminates. But if the input was `1` and this cell is `?` we hand over to Brian whose `{+?` will reset the loop on Chuck, and now we're printing `1`s forever (until the integer in the cell at the end of Brian's tape doesn't fit into memory any more, I suppose...).
### Bonus
Sp3000 and I have been golfing away at this for several days. We started out around 40 bytes and arrived at two completely different, but tied solutions at 26 bytes. Only when I started to write up the explanation for mine, did the 21-byte solution above occur to me. Many thanks to Sp for throwing ideas around and teaching each other some golfing tricks in B&C. :)
This is his 26 byte solution:
```
>,----{?{>1?0
#I<?_}<.<<<?
```
And this is mine:
```
,{>-<-?_0+?_1{<?
_®{?_{>.?
```
Where `®` is a byte with value 174 (e.g. just save the file as ISO 8859-1).
At the core mine works similarly to the 21-byte solution, in that `®` becomes `}` for input `1` and `~` (no-op) for input `0`, but the execution is much less elegant.
His solution is quite neat in that the source code is ASCII-only and that it doesn't require a loop to process the input. Instead, `----` turns `1` into `-` and `0` into `,` (a no-op for Chuck). That `-` will then change the first `?` on Brian's tape into a `>`, thereby creating different control flow for the `1`-case. 
[Answer]
# Thue, 34 bytes
```
1::=12
2::=~1
0::=~0
@::=:::
::=
@
```
**Explanation:**
`1::=12` Instances of the substring "1" can become "12"
`2::=~1` Instances of the substring "2" can be removed, printing "1"
`0::=~0` Instances of the substring "0" can be removed, printing "0"
`@::=:::` Instances of the substring "@" can be replaced with strings from the input
`::=` End list of substitution rules
`@` The initial string is "@"
[Answer]
# Arnold C, 134 bytes
```
IT'S SHOWTIME
HEY CHRISTMAS TREE i
YOU SET US UP 0         //or 1
STICK AROUND i
TALK TO THE HAND 1
CHILL
TALK TO THE HAND 0
YOU HAVE BEEN TERMINATED
```
While this isn't as entertaining as the other ArnoldC [answer](https://codegolf.stackexchange.com/a/62777/39328), it's golfed. For example, indentation is unnecessary, and so are the macros `@NO PROBLEMO` and `@I LIED`.
Tested with [this version of the language](http://mapmeld.github.io/ArnoldC/), which cannot take input.
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), 5 ~~6~~ bytes
Cubix is @ETHproductions new 2 dimensional language where the commands are wrapped around the faces of a cube. [Online interpreter](https://ethproductions.github.io/cubix)
Thanks to @ETHproductions for the saving.
```
!I\@O
```
This ends up expanded out to the cube
```
  !
I \ @ O
  .
```
This starts with the `I` command. Input an integer onto the stack.  
`\`, redirects the instruction pointer down over the no op.  
`O`, outputs the numeric value of top of stack.  
`!`, skip the next command (`@`) if top of stack true. This will jump the `\`  redirect if 1  
`\`, redirects the instruction pointer to the `@` exit program.  
This takes advantage of the fact the stack isn't popped by the `O ? !` commands.
[Answer]
## [Foo](https://esolangs.org/wiki/Foo), 6 bytes
```
&1($i)
```
Input is hardcoded as the second character, since Foo doesn't have STDIN input. Don't we agree that Foo is awesome now? :)
### Explanation
```
&1          Set current cell to 1
  (  )      Do-while loop (or, at least according to the interpreter)
   $i       Print current cell as int
```
[Answer]
# Perl, ~~18 + 1 = 19~~ 13 + 1 = 14 bytes
```
print while$_
```
Run like this:
```
echo -n NUM | perl -p truth.pl
```
Thanks to ThisSuitIsBlackNot (who is way better at Perl golfing than me) for golfing off five bytes.
]