# Print the ASCII table

The task is to display n characters of the ASCII table.

You may write a function (or a program that takes the argument as a parameter, STDIN is allowed as well) that takes a parameter n, which will be the index of the last character to print.

The task is quite simple, so as an example here's a possible implementation in Python 2.7:

(lambda n:map(chr, range(n)))(256)


As I said it's a simple task. So this is code-golf and the shortest codes wins!

EDIT

As some of you pointed out this code doesn't print the result. It's just an example since I might struggle explaining the problem in english ;-).

EDIT2

Feel free to post the answer in any programming language, even if it's not the shortest code. Maybe there are some interesting implementations out there!

EDIT3

Fixed the example so it prints the result.

• 1. Does it have to be a function? 2. According to your reference code, n would be the first character that is not printed. Commented Oct 28, 2014 at 12:49
• Actually the reference code prints nothing. It just returns a list of the characters and lets the REPL do whatever it wants with the result. Commented Oct 28, 2014 at 12:50
• Can somebody please explain the downvote? I am sorry if my english isn't that good. If there's something unclear within the question please tell me. Commented Oct 28, 2014 at 12:57
• for x in range(input()):print chr(x) Would actually print the characters, if you want to edit your example. Commented Oct 28, 2014 at 12:59
• nota [i for i in range(n)] is quite similar to range(n) Commented Oct 28, 2014 at 19:22

# brainfuck - 169146 142 bytes

-[+>+[+<]>+]>+>>,[>,]<[<]<[->>[->]<[<]<]>>>[[<[-<+<+<+>>>]+++++++++[<[-<+>]<<[-<+>>>+<<]<[->+<]>>>>-]]<,<<,>[->>>+<<<]>>>---------->]<-[->.+<]


Limitations:

• EOF must be 0
• Requires 8-bit wrapping cells
• Because of ^, mods input by 256

Not the shortest answer here, but hey, brainfuck! This would be a really, really good brainfuck challenge, except for the fact that it requires human readable input without guaranteeing the number of digits. I could have required input to have leading zeroes to make it 3 characters long, but what fun is that? :D One major problem with taking input this way is that brainfuck's only branching or looping structure checks if the current cell is zero or not. When the input can contain zeroes, it can cause your code to take branches it shouldn't be taking. To solve this problem, I store each digit of input plus 1, then subtract the excess at the last possible second. That way, I always know where my zeroes are.

I did say that this would have been a great brainfuck challenge without having to parse input. Why is that? Well, let's pretend that we don't take a numeric input. We'll say the challenge is "Given a byte of input, output all ASCII characters below that byte". Here's what my answer would be:

# brainfuck - 8 bytes

,[->.+<]


It's quite a difference! The real program uses 135 instructions to collect the input (over 95% of the program!), just because it's a human typing it. Store the number as a byte and give that to me, and it only takes one.

(Fun fact: If you understood the hypothetical program, then congratulations! You understand brainfuck in its entirety. The whole language has only eight commands, and that program happens to use each one exactly once.)

Explanation

-[+>+[+<]>+]>+               abuse 8 bit wrapping to put 47 in cell 4

>>,[>,]                      starting in cell 6; get each character of input

<[<]<[->>[->]<[<]<]          subtract the value of cell 4 from each input character
'0' has an ascii value of 47 so subtracting 47 from each
digit gives you that digit's value plus 1

>>>[                         if the number is in more than one cell
(when the program first starts this means "if the input has
more than one digit")

[<[-<+<+<+>>>]               copy first input cell to 3 new cells

+++++++++[<[-<+>]<<          do some fancy addition magic to multiply that value by 10
[-<+>>>+<<]<[->+<]>>>>-]]

<,<<,>                       clean up a bit (abusing comma to set cells to 0)

[->>>+<<<]>>>                add the value to the next cell of input

----------                   because we multiplied (the digit plus 1) by 10; the answer
is 10 too high; so subtract 10

>]                           if the input is still in multiple cells; do the song and
dance again (multiply by 10; add to next cell; subtract 10)

<-                           we never got a chance to fix the final digit; so it's still 1
too high

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;         we have now finished processing input         ;;
;;     the tape is empty except for the current cell     ;;
;;  the current cell contains the number that was input  ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

[                            while the cell containing input != 0

-                            subtract 1 from it

>.+                          go a cell to the right; output that cell; then add 1

<]                           repeat

• Nice! Definitely +1 for the effort :-) Commented Oct 28, 2014 at 15:24
• You could save some bytes on the outputting part: >[-]<[->.+<] Set cell next to current cell to 0, then count down the current cell while increasing the cell next to it and simultaneously printing the value. Commented Oct 28, 2014 at 15:59
• @shu That's an excellent point! I didn't think of that at all. In addition to being shorter, it fixes the problem I had with choking on large inputs and it's probably faster! Thanks :) Commented Oct 29, 2014 at 12:59
• Yeah, it's much, much faster now. I also didn't need the >[-]< part because I was already next to an empty cell. :) Commented Oct 29, 2014 at 13:09
• Commented Feb 13, 2017 at 0:18

# CJam, 4 bytes

ric,


Full program that reads from STDIN (input field in the online interpreter).

This simply executes range(chr(int(input()))), taking advantage of the fact that , gives a return an array of characters if its argument is a character.

I call dibs on c, (2 bytes), just in case that assuming the input is already on the stack turns out to be allowed.

• Do you have to specify some input? The online runner just outputs the code itself. Commented Oct 28, 2014 at 12:52
• @manatwork: Just a sec. You have to hurry when you post these... ;) Commented Oct 28, 2014 at 12:53
• I am a little confused by this. The character at 0 ( aka 0c )prevents anything else from being printed after it. ric,( seems to work fine. This means the code doesn't work. Commented Oct 28, 2014 at 18:03
• @kaine: Internet Explorer is written in C++, which does not use null-terminated strings. According to this, null characters are parse errors in HTML 5; the browser must replace it with a � or abort processing the document. Commented Oct 28, 2014 at 18:55
• Keep in mind that you have to enter a sufficiently large n, because the first few dozen of ASCII characters are non-printable characters. Fun fact: this program also outputs the Unicode table, for example n=9999 Commented Oct 29, 2014 at 15:28

## Pyth, 4 bytes

VQCN


Basically a translation of the Python 3 program:

for N in range(eval(input())):print(chr(N))


# Befunge 93 - 23 21

&> :#v_,>:#,_@
^-1:<


# Befunge 93 - 15 13 (by Ingo Bürk)

This one prints the list in reverse, but OP only said we need to print the first n characters, not that it has to be in order.

&>::>v
@^-1,_


Might not be golfable any further without moving on to Befunge98 (for the ";" operator, see @Kasran's answer)

Try it here:

function BefungeBoard(source, constraints) {
constraints = constraints || {
width: 80,
height: 25
};

this.constraints = constraints;
this.grid = source.split(/\r\n|[\n\v\f\r\x85\u2028\u2029]/).map(function (line) {
return (line + String.repeat(' ', constraints.width - line.length)).split('');
});
for (var i = this.grid.length; i < constraints.height; i++) {
this.grid[i] = String.repeat(' ', constraints.width).split('');
}

this.pointer = {
x: 0,
y: 0
};

this.direction = Direction.RIGHT;
}

BefungeBoard.prototype.nextPosition = function () {
var vector = this.direction.toVector(),
nextPosition = {
x: this.pointer.x + vector[0],
y: this.pointer.y + vector[1]
};

nextPosition.x = nextPosition.x < 0 ? this.constraints.width - 1 : nextPosition.x;
nextPosition.y = nextPosition.y < 0 ? this.constraints.height - 1 : nextPosition.y;

nextPosition.x = nextPosition.x >= this.constraints.width ? 0 : nextPosition.x;
nextPosition.y = nextPosition.y >= this.constraints.height ? 0 : nextPosition.y;

return nextPosition;
};

this.pointer = this.nextPosition();
}
};

BefungeBoard.prototype.currentToken = function () {
return this.grid[this.pointer.y][this.pointer.x];
};

BefungeBoard.prototype.nextToken = function () {
var nextPosition = this.nextPosition();
return this.grid[nextPosition.y][nextPosition.x];
};

var Direction = (function () {
var vectors = [
[1, 0],
[-1, 0],
[0, -1],
[0, 1]
];

function Direction(value) {
this.value = value;
}

Direction.prototype.toVector = function () {
return vectors[this.value];
};

return {
UP: new Direction(2),
DOWN: new Direction(3),
RIGHT: new Direction(0),
LEFT: new Direction(1)
};
})();

function BefungeStack() {
this.stack = [];
}

BefungeStack.prototype.pushAscii = function (item) {
this.pushNumber(item.charCodeAt());
};

BefungeStack.prototype.pushNumber = function (item) {
if (isNaN(+item)) {
throw new Error(typeof item + " | " + item + " is not a number");
}

this.stack.push(+item);
};

BefungeStack.prototype.popAscii = function () {
return String.fromCharCode(this.popNumber());
};

BefungeStack.prototype.popNumber = function () {
return this.stack.length === 0 ? 0 : this.stack.pop();
};

function Befunge(source, constraints) {
this.board = new BefungeBoard(source, constraints);
this.stack = new BefungeStack();
this.stringMode = false;
this.terminated = false;

this.digits = "0123456789".split('');
}

Befunge.prototype.run = function () {
for (var i = 1; i <= (this.stepsPerTick || 10); i++) {
this.step();
if (this.terminated) {
return;
}
}

requestAnimationFrame(this.run.bind(this));
};

Befunge.prototype.step = function () {
this.processCurrentToken();
};

Befunge.prototype.processCurrentToken = function () {
var token = this.board.currentToken();
if (this.stringMode && token !== '"') {
return this.stack.pushAscii(token);
}

if (this.digits.indexOf(token) !== -1) {
return this.stack.pushNumber(token);
}

switch (token) {
case ' ':
while ((token = this.board.nextToken()) == ' ') {
}
return;
case '+':
return this.stack.pushNumber(this.stack.popNumber() + this.stack.popNumber());
case '-':
return this.stack.pushNumber(-this.stack.popNumber() + this.stack.popNumber());
case '*':
return this.stack.pushNumber(this.stack.popNumber() * this.stack.popNumber());
case '/':
var denominator = this.stack.popNumber(),
numerator = this.stack.popNumber(),
result;
if (denominator === 0) {
result = +prompt("Illegal division by zero. Please enter the result to use:");
} else {
result = Math.floor(numerator / denominator);
}

return this.stack.pushNumber(result);
case '%':
var modulus = this.stack.popNumber(),
numerator = this.stack.popNumber(),
result;
if (modulus === 0) {
result = +prompt("Illegal division by zero. Please enter the result to use:");
} else {
result = Math.floor(numerator / modulus);
}

return this.stack.pushNumber(result);
case '!':
return this.stack.pushNumber(this.stack.popNumber() === 0 ? 1 : 0);
case '':
return this.stack.pushNumber(this.stack.popNumber() < this.stack.popNumber() ? 1 : 0);
case '>':
this.board.direction = Direction.RIGHT;
return;
case '<':
this.board.direction = Direction.LEFT;
return;
case '^':
this.board.direction = Direction.UP;
return;
case 'v':
this.board.direction = Direction.DOWN;
return;
case '?':
this.board.direction = [Direction.RIGHT, Direction.UP, Direction.LEFT, Direction.DOWN][Math.floor(4 * Math.random())];
return;
case '_':
this.board.direction = this.stack.popNumber() === 0 ? Direction.RIGHT : Direction.LEFT;
return;
case '|':
this.board.direction = this.stack.popNumber() === 0 ? Direction.DOWN : Direction.UP;
return;
case '"':
this.stringMode = !this.stringMode;
return;
case ':':
var top = this.stack.popNumber();
this.stack.pushNumber(top);
return this.stack.pushNumber(top);
case '\\':
var first = this.stack.popNumber(),
second = this.stack.popNumber();
this.stack.pushNumber(first);
return this.stack.pushNumber(second);
case '': return this.stack.popNumber(); case '#': return this.board.advance(); case 'p': return this.board.grid[this.stack.popNumber()][this.stack.popNumber()] = this.stack.popAscii(); case 'g': return this.stack.pushAscii(this.board.grid[this.stack.popNumber()][this.stack.popNumber()]); case '&': return this.stack.pushNumber(+prompt("Please enter a number:")); case '~': return this.stack.pushAscii(prompt("Please enter a character:")[0]); case '.': return this.print(this.stack.popNumber()); case ',': return this.print(this.stack.popAscii()); case '@': this.terminated = true; return; } }; Befunge.prototype.withStdout = function (printer) { this.print = printer; return this; }; Befunge.prototype.withOnAdvance = function (onAdvance) { this.board.onAdvance = onAdvance; return this; }; String.repeat = function (str, count) { var repeated = ""; for (var i = 1; i <= count; i++) { repeated += str; } return repeated; }; window['requestAnimationFrame'] = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function (callback) { window.setTimeout(callback, 1000 / 60); }; (function () { var currentInstance = null; function resetInstance() { currentInstance = null; } function getOrCreateInstance() { if (currentInstance !== null && currentInstance.terminated) { resetInstance(); } if (currentInstance === null) { var boardSize = Editor.getBoardSize(); currentInstance = new Befunge(Editor.getSource(), { width: boardSize.width, height: boardSize.height }); currentInstance.stepsPerTick = Editor.getStepsPerTick(); currentInstance.withStdout(Editor.append); currentInstance.withOnAdvance(function (position) { Editor.highlight(currentInstance.board.grid, position.x, position.y); }); } return currentInstance; } var Editor = (function (onExecute, onStep, onReset) { var source = document.getElementById('source'), sourceDisplay = document.getElementById('source-display'), sourceDisplayWrapper = document.getElementById('source-display-wrapper'), stdout = document.getElementById('stdout'); var execute = document.getElementById('execute'), step = document.getElementById('step'), reset = document.getElementById('reset'); var boardWidth = document.getElementById('board-width'), boardHeight = document.getElementById('board-height'), stepsPerTick = document.getElementById('steps-per-tick'); function showEditor() { source.style.display = "block"; sourceDisplayWrapper.style.display = "none"; source.focus(); } function hideEditor() { source.style.display = "none"; sourceDisplayWrapper.style.display = "block"; var computedHeight = getComputedStyle(source).height; sourceDisplayWrapper.style.minHeight = computedHeight; sourceDisplayWrapper.style.maxHeight = computedHeight; sourceDisplay.textContent = source.value; } function resetOutput() { stdout.value = null; } function escapeEntities(input) { return input.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); } sourceDisplayWrapper.onclick = function () { resetOutput(); showEditor(); onReset && onReset.call(null); }; execute.onclick = function () { resetOutput(); hideEditor(); onExecute && onExecute.call(null); }; step.onclick = function () { hideEditor(); onStep && onStep.call(null); }; reset.onclick = function () { resetOutput(); showEditor(); onReset && onReset.call(null); }; return { getSource: function () { return source.value; }, append: function (content) { stdout.value = stdout.value + content; }, highlight: function (grid, x, y) { var highlighted = []; for (var row = 0; row < grid.length; row++) { highlighted[row] = []; for (var column = 0; column < grid[row].length; column++) { highlighted[row][column] = escapeEntities(grid[row][column]); } } highlighted[y][x] = '<span class="activeToken">' + highlighted[y][x] + '</span>'; sourceDisplay.innerHTML = highlighted.map(function (lineTokens) { return lineTokens.join(''); }).join('\n'); }, getBoardSize: function () { return { width: +boardWidth.innerHTML, height: +boardHeight.innerHTML }; }, getStepsPerTick: function () { return +stepsPerTick.innerHTML; } }; })(function () { getOrCreateInstance().run(); }, function () { getOrCreateInstance().step(); }, resetInstance); })(); .container { width: 100%; } .so-box { font-family:'Helvetica Neue', Arial, sans-serif; font-weight: bold; color: #fff; text-align: center; padding: .3em .7em; font-size: 1em; line-height: 1.1; border: 1px solid #c47b07; -webkit-box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset; text-shadow: 0 0 2px rgba(0, 0, 0, 0.5); background: #f88912; box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset; } .control { display: inline-block; border-radius: 6px; float: left; margin-right: 25px; cursor: pointer; } .option { padding: 10px 20px; margin-right: 25px; float: left; } input, textarea { box-sizing: border-box; } textarea { display: block; white-space: pre; overflow: auto; height: 75px; width: 100%; max-width: 100%; min-height: 25px; } span[contenteditable] { padding: 2px 6px; background: #cc7801; color: #fff; } #controls-container, #options-container { height: auto; padding: 6px 0; } #stdout { height: 50px; } #reset { float: right; } #source-display-wrapper { display: none; width: 100%; height: 100%; overflow: auto; border: 1px solid black; box-sizing: border-box; } #source-display { font-family: monospace; white-space: pre; padding: 2px; } .activeToken { background: #f88912; } .clearfix:after { content:"."; display: block; height: 0; clear: both; visibility: hidden; } .clearfix { display: inline-block; } * html .clearfix { height: 1%; } .clearfix { display: block; } <div class="container"> <textarea id="source" placeholder="Enter your Befunge-93 program here" wrap="off">&> :#v_,>:#,_@ ^-1:<</textarea> <div id="source-display-wrapper"> <div id="source-display"></div> </div> </div> <div id="controls-container" class="container clearfix"> <input type="button" id="execute" class="control so-box" value="► Execute" /> <input type="button" id="step" class="control so-box" value="Step" /> <input type="button" id="reset" class="control so-box" value="Reset" /> </div> <div id="stdout-container" class="container"> <textarea id="stdout" placeholder="Output" wrap="off" readonly></textarea> </div> <div id="options-container" class="container"> <div class="option so-box">Steps per Tick: <span id="steps-per-tick" contenteditable>500</span> </div> <div class="option so-box">Board Size: <span id="board-width" contenteditable>80</span> x <span id="board-height" contenteditable>25</span> </div> </div> • I hope you don't mind that I used an inline interpreter from here :) Commented Oct 29, 2014 at 19:36 • The question doesn't state that we must print it in any order, so this is five byte shorter: &> #- #1:# :#,_@ (it just prints it in reverse) Commented Oct 29, 2014 at 19:55 • I shaved off another bytes for a total of 15. Because of newlines I will edit it into your post. Commented Oct 29, 2014 at 19:57 • Well played on the extra golfing :) As for the inline interpreter, I wasn't aware there was one. It's great, thanks :) Commented Oct 30, 2014 at 8:47 • The interpreter is new from the linked challenge. I just thought I'd actually use it when I saw your answer. :) Commented Oct 30, 2014 at 8:58 # Java, 1511287762 56 bytes First try at code-golfing. void f(int n){for(char i=0;++i<=n;System.out.print(i));}  Usage: import java.util.Scanner; class A { public static void main(String[] a) { int num = new Scanner(System.in).nextInt(); new A().f(num); } void f(int n) { for (char i = 0; ++i <= n; System.out.print(i)); } }  Thanks to @Shujal, @flawr, @Ingo Bürk and @Loovjo for the serious byte reduction. • You can save some chars by declaring the int while opening the scanner: int i,n=new Scanner(... and changing the loop to for(;++i<n;). Also, you don't need to invoke Character.toString. You can just feed System.out a char value and it will happily output it. Commented Oct 28, 2014 at 16:03 • The challenge allows the use of your a as input. And I think you can shorten the for loop by abusing the increment place as loop body: for(;++i<n;System.out.print((char)i)); (but you might have to change the initialization or end value by +- 1) Commented Oct 29, 2014 at 19:11 • You are allowed to write a function, so no need for an entire class and everything. Commented Oct 29, 2014 at 19:33 • @RodolfoDias Are you sure? Obviously, ++i<n+1 should be equivalent to ++i<=n. Note the = in there, however! It just saves one byte. It works for me. Commented Oct 29, 2014 at 21:01 • So we come down to void f(int n){int i=0;for(;++i<=n;System.out.print((char)i));} which is 62 bytes. At least I don't see more to golf now. :) Commented Oct 30, 2014 at 6:53 ## APL,5 ⎕UCS⍳  Example usage: ⎕UCS⍳256  • You don't have to make a dfn. Just ⎕UCS⍳ would work fine. So 5 chars Commented Oct 28, 2014 at 13:34 • You don't have to support code points over 127. Just ↑⎕AV would work fine. So 4 chars – Adám Commented Feb 7, 2016 at 21:43 # JavaScript, ES6 - 5258565344 42 bytes n=>String.fromCharCode(...Array(n).keys())  Paste this into the Firefox console. Run as f(NUM). Had to make it longer because the first didn't properly accept input. Down 3, thanks edc65! Down to 44 thanks to Swivel! • This doesn't really handle neither parameter nor input. Commented Oct 28, 2014 at 14:14 • Just change the 70 to a different number; that's the input. Commented Oct 28, 2014 at 14:17 • Okay, i updated it to take input, at the cost of 6 bytes. Commented Oct 28, 2014 at 14:25 • -2: f=n=>[...Array(n)].map((v,i)=>String.fromCharCode(i)) Commented Oct 28, 2014 at 18:13 • 44 Characters! f=n=>String.fromCharCode(...Array(n).keys()) Commented Jul 21, 2016 at 20:57 # Haskell, 17 23 bytes flip take['\0'..]  Not sure if it is possible to do any better without imports. ## Edit My first solution didn't actually print the result, so allow 6 more chars for that: print.flip take['\0'..]  Also, not shorter (25 chars with printing, 19 without), but an interesting alternate approach (it requires 'Data.List', though): print.((inits['\0'..])!!)  • This doesn't actually print the result. – user344 Commented Oct 29, 2014 at 15:22 • @nyuszika7h now it does Commented Oct 29, 2014 at 16:00 • (take['\0'..]) saves a byte. Commented Aug 16, 2017 at 7:13 # Perl, 17 bytes say chr for 0.._

• Too many parenthesis. print chr for 0..$ARGV[0] Commented Oct 29, 2014 at 15:29 • You're right! It has been a while since I used perl Commented Oct 29, 2014 at 15:46 • You can use shift instead of $ARGV[0] to save 2 bytes.
– user344
Commented Oct 29, 2014 at 16:32
• If you are allowed to print the characters on different lines, you can use say. Also, the character count is shorter if you do it as a one-liner with -n. echo "90" | perl -nE'say chr for 0..$_' would count as 18 characters. 17 for say chr for 0..$_ plus 1 for the n. Commented Oct 29, 2014 at 17:26
• You're right. But say won't work with every version of perl. Commented Oct 30, 2014 at 8:32

# awk - 27

{while(i<$0)printf"%c",i++}  To give the parameter on stdin run it like: awk '{while(i<$0)printf"%c",i++}' <<<96


Just for fun: The "think positive version" starting with a definitive yes:

yes|head -96|awk '{printf"%c",NR-1}'


NR-1 is needed to print (char)0 for NR==1.    :-(

And why don't we have a no command? That's kinda mean!

• alias no='yes no'
– user344
Commented Oct 29, 2014 at 15:25
• ...but then I'd have to count the chars of that alias definition too... :-(
– user19214
Commented Oct 29, 2014 at 15:49
• This made my day. @nyuszika7h. My gosh XD thanks for this Commented Feb 16, 2021 at 22:01

# Bash+BSD common utilities, 9 bytes

jot -c $1  # GNU dc, 20 bytes ?sc_1[1+dPdlc>m]dsmx  # C, 313028 27 k;f(n){putch(k++)<n&&f(n);}  Since putch is nonstandard, here's the fully compliant version: k;f(n){putchar(k++)<n&&f(n);}  Must be called from main: main(){f(255);}  EDIT: Improved by taking advantage of putchar return value EDIT 2: Reduced by another character through recursion • putch is a non-standard function. Also, may I ask why this answer was downvoted? Commented Jun 12, 2015 at 0:37 • @Stuntddude I'll add an alternatve version that uses putchar, and no idea why this is downvoted. After all, it is one of the shorter ones. Commented Jun 12, 2015 at 0:39 ## CJam, 3 ,:c  I assumed the argument to be the top stack element. Example usage: 256,:c ri,:c  # Ruby, 30 characters puts (0..$*[0].to_i).map &:chr


## J - 5 bytes

{.&a.


{. is Head, a. is Alphabet ( a list of all chars) and & Bonds them, generating a monadic verb called like:

{.&a. 100 NB. first 100 characters


Note: It seems this does not work interactively: Jconsole and jQt seems to set up a translation, outputting box characters instead of some control characters. In a script or from the commandline, it does work though:

  ijconsole <<< '127 {. a.' | hd

• Notice that the alphabet is not exactly ASCII. Commented Jun 30, 2015 at 13:10
• Up to {.&a. 127, it is no? Commented Jul 1, 2015 at 6:44
• No because J has box drawing characters instead of some of the control characters. Commented Jul 1, 2015 at 6:46
• Actually, writing this to a file and inspecting it with a hex viewer tells me that J outputs the correct values (0x00 0x01, ...) . it's only the J interpreter/ IDE interpretting those values as boxdrawing characters instead of control characters. It does exactly the same as all other languages using char or equivalents do. Commented Jul 1, 2015 at 7:07
• That's weird because I tested it on my UNIX box and it did indeed output Unicode characters for some of the code-points. Commented Jul 1, 2015 at 7:16

# gs2, 2 bytes

V.


This should be competing, I think! It would’ve worked even in the early days of gs2. Try it here.

• Successfully tested with this version, which predates the challenge by a month. Commented Feb 5, 2016 at 18:02

## Brainfuck, 44 bytes

,
[
<[>++++++++++<-]
-[>-<-----]
>+++>,
]
<[>.+<-]

Expects a decimal string without a trailing newline.

Try it online.

Reading integers in the range [0, max_cell_size] in brainfuck is not difficult. I encourage you to invent a clean method on your own. I consider this a beginner level exercise. (The reverse operation of printing a cell's numeric value is more involved, and could be considered an intermediate level task.)

Here's a 58-byte version that can handle 256 on 8-bit implementations:

,
[
<[<+> >++++++++++<-]
-[>-<-----]
>+++>,
]
<[>]
-<<[>.]
>[>+.<-]

• Why haven't I thought of this??? This is ingenious!!!
– FinW
Commented Feb 25, 2017 at 19:03
• Can I borrow this to use on future answers?
– FinW
Commented Feb 25, 2017 at 19:11
• @FinW I'm guessing you don't know about this meta post. Commented Feb 26, 2017 at 2:37

# √ å ı ¥ ® Ï Ø ¿ , 3 bytes

Note: Language post-dates challenge

IrW


### Explanation

I   › Take input from command line, evaluate and push to stack
r  › Push the range from 0 to top value + 1
W › Output the whole stack as Unicode characters


# Alternate Solution

As pointed out by @FlipTack in his Java answer, it is not clear if the OP wants us to print up to and including the input or excluding the input.

If the second is true, the solution below is the correct answer.

IrPW


### Explanation

I    › Take input from command line, evaluate and push to stack
r   › Push the range from 0 to top value + 1
P  › Pop the top value from the stack
W › Output the whole stack as Unicode characters


# Golfscript - 5

Thanks to @Dennis

~,''+

• ~,""+ is shorter and correctly processes input from STDIN. Commented Oct 28, 2014 at 14:04
• @Dennis That doesn't produce any output for me... Commented Oct 28, 2014 at 14:15
• Are you using the online interpeter? To correctly simulate input from STDIN, you have to use, e.g., ;"65", since the input from STDIN will always be a string. Commented Oct 28, 2014 at 14:17
• @Dennis Oh thanks that works now! Commented Oct 28, 2014 at 14:25

## Lua - 43 41 Bytes

for i=1,arg[1]do print(string.char(i))end

• You can shorten this by a byte a=""for i=1,arg[1]do print(a.char(i))end Commented Oct 31, 2015 at 15:21
• You can shorten this by 2 bytes for i=1,arg[1]do print(("").char(i))end Commented Jul 22, 2016 at 9:25

# Befunge 98, 22

&:00pv>0gk,@
0::-1<^j


Kind of sad that this is so long.

&:00p        ; gets numerical input, stores a copy at cell (0,0)               ;
v       ; IP goes down                                                    ;

<       ; IP goes left, so I execute 1-::0j^                             ;
::-1        ; (1-::) subtract one from our number and duplicate it twice      ;
0           ; (0) compare the number with 0, push 1 if greater else 0        ;
<^j     ; if the result was 0, go up, otherwise continue going left       ;

>0gk,  ; get the value at cell (0,0), print that many numbers from stack ;
@ ; terminate program                                               ;


# Python 3.4 - 36 bytes / 43 bytes

print(*map(chr,range(int(input()))))
print(*map(chr,range(int(input()))),sep='')


255 input()

How this works is:

1. Get upper limit of range
2. Generate a range of the table.
3. Map the range to chr function ( takes int, returns ascii ).
4. Consume the map via splat argument expansion ( number -> character -> print! )

The second one just removes the space separating each character in exchange for 7 bytes.

• You could very much make this into a lambda, as the question states this, and in Python 2, map returns a list, so you could just do f=lambda i:map(chr,range(i)) Commented Oct 29, 2014 at 6:14
• That's true, and my initial solution was similar but I didn't want to use a lambda so that I could immediately print output. I wish map kept the trend of returning a list instead of an iterator, even if it is more pythonic that way. Commented Oct 29, 2014 at 6:27

# Pascal 87

program _;var c:char;n:byte;begin n:=0;readln(n);for c:=chr(0)to chr(n)do write(c);end.


# Pascal 73

program _;var c,n:byte;begin readln(n);for c:=0to n do write(chr(c));end.


Builds and runs fine from http://www.onlinecompiler.net/pascal

• FreePascal (and if I remember correctly, Turbo Pascal too) only needs 60 of those characters: var c,n:byte;begin read(n);for c:=0to n do write(chr(c))end. pastebin.com/aFLVTuvh Commented Oct 29, 2014 at 16:00
• Quite possibly, I've only used Delphi. But someone edited that out of the title. Commented Jun 4, 2018 at 15:26

# x86 ASM (Linux) (many many bytes unless you compile it)

Written as a function, assumes parameter is passed in AX (I forget the number for the read syscall) Also doesn't preserve [SP] or BX.

test ax,ax
jz @Done
mov [sp],ax
@Loop:
mov ax,4
mov bx,1
mov cx,sp
mov dx,1
int 0x80
sub [sp],1  ; Can I do this?  Or do I need to load/sub/store separately?
jnz @Loop
@Done:
ret

• (I should have put a F00F exploit in there, it's not like anyone will run it anyway) Commented Oct 29, 2014 at 13:09
• I was going to run this. I'm not going to run this now. Commented Oct 30, 2014 at 2:43

# Perl - 29

sub f{print map{chr}0..shift}


# Ruby, 23

f=->n{puts *?\0..n.chr}


## Explanation

• Input is taken as the argument to a lambda. It expects an Integer.
• The "destructuring operator" (*) invokes #to_ary on the Range to print every character on its own line.

# Julia: 20 characters (REPL)

This is close to the question's example: just generates the characters and let the REPL to do whatever it wants with them.

f(n)=map(char,[0:n])


## Julia: 33 characters

Prints each character in a separate line.

print(map(char,[0:int(ARGS[1])]))


# M (MUMPS) - 21

R n F i=1:1:n W $C(i) In expanded form: READ n FOR i=1:1:n WRITE$CHAR(i)

## T-SQL: 68 63

As a print loop

DECLARE @i INT=64,@ INT=0A:PRINT CHAR(@)SET @+=1IF @<=@i GOTO A


## T-SQL: 95 86

As a query

DECLARE @ INT=64SELECT TOP(@+1)CHAR(ROW_NUMBER()OVER(ORDER BY 0/0)-1)FROM sys.messages


Edit: Made changes and fixes pointed out by Muqo. Thanks. Fixes and golfing suggested by @t-clausen.dk

• For the loop, you can save 5 or so characters converting the WHILE to a GOTO with label. For the query, maybe specify msdb.sys.objects to guarantee enough objects. Also, it doesn't output CHAR(0). However, as consolation you can ORDER BY @.
– Muqo
Commented Oct 29, 2014 at 2:41
• Second answer is invalid. You can rewrite it this way and golf 9 characters: DECLARE @ INT=64SELECT TOP(@+1)CHAR(ROW_NUMBER()OVER(ORDER BY 0/0)-1)FROM sys.messages Commented Jul 11, 2016 at 14:26
• @t-clausen.dk not sure how I let that one through. Thanks for that. Commented Jul 11, 2016 at 18:37

# BrainFuck - 140 112 Bytes

,>,>,>-[>+<-----]>---[<+>-]<[<<<->->->-]<[>+<-]<[>>++++++++++<<-]<[>>>>++++++++++[<++++++++++>-]<<<<-]>>>[>.+<-]


Try It Here!

Saved 28 bytes by changing [<<<->>>->+<]>[<<<->>>->+<]>[<<<->>>-] to [<<<->->->-].

What it does

,>,>,>                                                              Takes three inputs
in three separate cells

-[>+<-----]>---[<+>-]<[<<<->->->-]<                                 Takes 48 off of each to
convert them to decimal

[>+<-]<[>>++++++++++<<-]<[>>>>++++++++++[<++++++++++>-]<<<<-]>>>    Combines them into a
three digit number by
multiplying the first
by 100, the second by
`