32
\$\begingroup\$

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.

\$\endgroup\$
14
  • \$\begingroup\$ 1. Does it have to be a function? 2. According to your reference code, n would be the first character that is not printed. \$\endgroup\$
    – Dennis
    Commented Oct 28, 2014 at 12:49
  • 2
    \$\begingroup\$ 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. \$\endgroup\$
    – manatwork
    Commented Oct 28, 2014 at 12:50
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – oopbase
    Commented Oct 28, 2014 at 12:57
  • 1
    \$\begingroup\$ for x in range(input()):print chr(x) Would actually print the characters, if you want to edit your example. \$\endgroup\$ Commented Oct 28, 2014 at 12:59
  • 2
    \$\begingroup\$ nota [i for i in range(n)] is quite similar to range(n) \$\endgroup\$
    – njzk2
    Commented Oct 28, 2014 at 19:22

101 Answers 101

1
\$\begingroup\$

PowerShell - 20

%{0..$_|%{[char]$_}}

Usage:
56 | %{0..$_|%{[char]$_}}
\$\endgroup\$
1
  • \$\begingroup\$ A bit debatable to call a piece of syntax that isn't even valid a program or function ;-) (you cannot use ForEach-Object standalone like that). The function part of that is the script block, but it won't ever work as a function, because the context ($_) is provided by ForEach-Object. You can shorten it a bit by casting the range to an array, by the way. \$\endgroup\$
    – Joey
    Commented Oct 30, 2014 at 7:32
1
\$\begingroup\$

Ruby - 35 33 bytes

Please note that I can't Ruby at all:

$*[0].to_i.times{|i|puts i.chr()}
\$\endgroup\$
6
  • 1
    \$\begingroup\$ As far as I know there is an alias for "puts" that is simply "p". So -3 bytes if that's correct? \$\endgroup\$
    – oopbase
    Commented Oct 28, 2014 at 13:28
  • 2
    \$\begingroup\$ @Forlan07, not really an alias. p is equivalent to puts whatever.inspect. \$\endgroup\$
    – manatwork
    Commented Oct 28, 2014 at 13:36
  • \$\begingroup\$ @manatwork OK, nice to know :-) \$\endgroup\$
    – oopbase
    Commented Oct 28, 2014 at 13:39
  • \$\begingroup\$ This prints every character on a separate line. Shouldn't it be print? \$\endgroup\$
    – user344
    Commented Oct 29, 2014 at 13:48
  • \$\begingroup\$ Fixed and 3 bytes shorter: puts (0..$*[0]).map(&:chr)*'' \$\endgroup\$
    – user344
    Commented Oct 29, 2014 at 13:51
1
\$\begingroup\$

Befunge-98, 26 20

0&;1-::0`j;;,$>:#,_@

It's longer than the other Befunge-98 answer, but it's not self-modifying and only uses one line. (Also, the pointer only moves to the right until it gets to the print loop.)

This is shorter now. Also, it's still not self-modifying. Hooray, jumping trickery!

\$\endgroup\$
1
\$\begingroup\$

If I'm allowed to have another answer in a different language, here goes...

Pascal: 91 bytes

PROGRAM A;VAR i,n:Integer;BEGIN
n:=0;readln(n);FOR i:=0 TO n DO
Write(chr(i));readln;END.

(just for kicks, really, I haven't messed in Pascal in ages)

\$\endgroup\$
3
  • 7
    \$\begingroup\$ Posting multiple answers is perfectly fine. \$\endgroup\$
    – Dennis
    Commented Oct 28, 2014 at 20:55
  • \$\begingroup\$ @Dennis is well aware of this. Just check all the questions he's answered \$\endgroup\$ Commented Mar 15, 2017 at 22:00
  • \$\begingroup\$ You can re‑use your input/length variable n as the counter variable in the for-loop: program p(input,output);var n:integer;begin read(n);for n:=1 to n do write(chr(n))end. \$\endgroup\$ Commented Nov 5, 2022 at 18:25
1
\$\begingroup\$

Python 3 — 51 bytes

lambda n:sys.stdout.buffer.write(bytes(range(n+1)))

This is a variation of a line I keep in my shell history for when I need to refer to the ASCII table.

It first calls range(), passing n + 1 as the sole argument. When used like this, range() returns an iterable of integers between 0 (inclusive) and the argument (exclusive—hence the need for the +1). The iterable is then passed to bytes(), which returns a bytestring, interpreting each integer as one byte. The bytestring is then written directly to the buffer for stdout (passing it to sys.stdout.write() or print() would result in an exception; those accept strings, not bytestrings).

Note that n must not be greater than 255. If it is, bytes() will raise an exception, because values greater than 255 do not fit in a single byte.

Also note that this doesn't bind the function to a name. I'm assuming that's acceptable, given that it does still create the function.

\$\endgroup\$
2
  • \$\begingroup\$ 1. There's no need for all of that: lambda n:print(str(bytes(range(n+1)))) is just 38 characters. 2. If you go with your current method, you need to include import sys. \$\endgroup\$
    – Beta Decay
    Commented Oct 29, 2014 at 15:18
  • \$\begingroup\$ Actually, just lambda n:print(bytes(range(n+1))) works perfectly well. \$\endgroup\$
    – Beta Decay
    Commented Oct 29, 2014 at 15:20
1
\$\begingroup\$

LiveScript - 47

f=->alert String.fromCharCode.apply(,[0 to it])
\$\endgroup\$
1
\$\begingroup\$

Haskell - 16 22 characters

(`take`['\0'..])

Edit

Now printing the result

print.(`take`['\0'..])
\$\endgroup\$
3
  • \$\begingroup\$ nice trick to get rid of a character \$\endgroup\$ Commented Oct 29, 2014 at 9:32
  • \$\begingroup\$ This doesn't actually print the result. \$\endgroup\$
    – user344
    Commented Oct 29, 2014 at 15:20
  • \$\begingroup\$ @JanDvorak he pretty much removed the space, as (``) does the same thing as flip here, in just as many characters... \$\endgroup\$ Commented Oct 29, 2014 at 15:57
1
\$\begingroup\$

F# - 66 characters

[<EntryPoint>]
let m a=
 for x in char 0..a.[0].[0]do printfn"%c"x
 0
\$\endgroup\$
1
\$\begingroup\$

PowerShell, 20

[char[]](0.."$args")
\$\endgroup\$
1
\$\begingroup\$

PHP - 36

If PHP Notice are set to off then this:

<? for(;$i<$argv[1];)echo chr($i++);

PHP - 42

Otherwise:

<? for($i=0;$i<$argv[1];$i++)echo chr($i);
\$\endgroup\$
11
  • \$\begingroup\$ I think you can remove the PHP tag. JS answers typically don't include script tags, either. \$\endgroup\$
    – Ingo Bürk
    Commented Oct 30, 2014 at 7:19
  • \$\begingroup\$ OK, ty. First post so not sure how it goes :) \$\endgroup\$
    – Dexa
    Commented Oct 30, 2014 at 9:49
  • \$\begingroup\$ @IngoBürk That may be because Node.js doesn't need any script tags. You need <?php (or <? if short tags are enabled) for any PHP script, though. \$\endgroup\$
    – user344
    Commented Oct 30, 2014 at 19:12
  • \$\begingroup\$ @nyuszika7h Node doesn't support ES6 and yet ES6 answers don't include tags. \$\endgroup\$
    – Ingo Bürk
    Commented Oct 30, 2014 at 19:17
  • \$\begingroup\$ I don't see your point. It does have partial support via --harmony, but that doesn't have to be counted unless perhaps the answer relies on Node-specific APIs. Script tags are just a way to include JavaScript in a HTML file, on the other hand even standalone PHP scripts need an opening tag or they won't work. \$\endgroup\$
    – user344
    Commented Oct 30, 2014 at 19:19
1
\$\begingroup\$

Rebol - 35 34

for n 0 do input 1[prin to-char n]
\$\endgroup\$
1
\$\begingroup\$

MATLAB: 13 bytes

@(n)char(0:n)

This is an anonymous function that prints the string.

MATLAB: 17 bytes

This one takes STDIN.

char(0:input(''))

I think these are pretty short for a non-golf language. :)

\$\endgroup\$
1
  • 1
    \$\begingroup\$ The standard tips for casting to chars when golfing in MATLAB / Octave: @(n)[0:n,'']. =) Saves you a byte! \$\endgroup\$ Commented Jan 12, 2016 at 14:18
1
\$\begingroup\$

C# - 65 63 52

c=>{for(var i='\0';i<=c;)System.Console.Write(i++);}

Inspired by Java solution

Usage:

public class Program
{
    public static void Main()
    {
        new System.Action<char>(c => {for(var i='\0';i<=c;)System.Console.Write(i++);})((char)255);
    }
}

Thanks to Martin for the help.

\$\endgroup\$
3
  • \$\begingroup\$ You can probably save two bytes by a) using var instead of char and b) by doing ...Write(i++) and leaving the third section of the for statement empty. \$\endgroup\$ Commented Jun 10, 2015 at 13:43
  • \$\begingroup\$ I just saw a python solution using lambdas. So would this be a valid solution: c=>{for(var i='\0';i<=c;)System.Console.Write(i++);}? \$\endgroup\$
    – pmudra
    Commented Jun 11, 2015 at 8:46
  • \$\begingroup\$ I'm not very familiar with C#'s lambdas, but I think so. \$\endgroup\$ Commented Jun 11, 2015 at 12:45
1
\$\begingroup\$

x86 DOS (11 bytes)

Takes parameter in CL

-u100
07AD:0100 mov ah,02
07AD:0102 cwd
07AD:0103 int 21
07AD:0105 inc dx
07AD:0106 cmp dl,cl
07AD:0108 jb 103
07AD:010A ret
07AD:010B 
\$\endgroup\$
1
\$\begingroup\$

Pip, 3 bytes (not competing)

The language is newer than the question, but happens to do very well with it:

C,a

a is the first command-line argument. The unary range operator , constructs a range of all numbers 0 <= n < a. Finally, C converts them to characters. The resulting list is autoprinted, by default without any delimiter. Works into Unicode range too!

\$\endgroup\$
1
\$\begingroup\$

Perl 6, 25 22 bytes

put (^@*ARGS[0])».chr
\$\endgroup\$
1
\$\begingroup\$

F#, 43 bytes

fun n->Seq.iter(printf"%c")['\x00'..char n]

That is...

fun n->                                     // A function that takes n
                           ['\x00'..char n] // Generates a list of chars from NUL to n
       Seq.iter(          )                 // For each one,
                printf"%c"                  // Print it!

I tried using \0 for NUL, but it doesn't work in F#. I couldn't get it under 4 characters, in any case. =P

\$\endgroup\$
1
\$\begingroup\$

Java, 125 bytes

class M{public static void main(String[]a){p(256);}static void p(int l){int i=-1;for(;i++<l;){System.out.println((char)i);}}}

Simply puts in the number of characters to print from the ascii table @ p(n) where n is the number of characters.

\$\endgroup\$
1
\$\begingroup\$

ES6, 42 bytes

Sorry for the necro.

n=>String.fromCharCode(...Array(n).keys())

If you need it as a program, 54 bytes:

alert(String.fromCharCode(...Array(+prompt()).keys()))

However for some reason I can't get the above to work as a Stack Snippet.

\$\endgroup\$
1
\$\begingroup\$

Lua, 37 Bytes

a=...for i=1,a do print(a.char(i))end
\$\endgroup\$
1
\$\begingroup\$

PHP - 47 bytes

<?=join(array_map('chr',range(0,$argv[1])));

Usage:

php ascii.php n
\$\endgroup\$
2
  • \$\begingroup\$ join does the same as implode and is 3 bytes shorter. \$\endgroup\$
    – Titus
    Commented Dec 14, 2016 at 13:20
  • \$\begingroup\$ @Titus good catch, updated! \$\endgroup\$
    – zamnuts
    Commented Dec 15, 2016 at 7:21
1
\$\begingroup\$

><>, 14 bytes

0:o1+:r:@=?;$!

Try it here!

Explanation

0              push 0 to the stack                [n, 0]
 :             duplicate the top value            [n, 0, 0]
  o            output it                          [n, 0]
   1+          add one                            [n, 1]
     :         duplicate top value                [n, 1, 1]
      r        reverse the stack                  [1, 1, n]
       :       duplicate the top value again      [1, 1, n, n]
        @      move the top value back twice      [1, n, 1, n]
         =?;   pop top two values, if equal, end  [1, n]
            $  swap top two stack values          [n, 1]
             ! skip next instruction (0)

or

0:o1+$1-:?!;$!

Try it here!

Explanation

0              push 0 to the stack                [n, 0]
 :             duplicate the top value            [n, 0, 0]
  o            output it                          [n, 0]
   1+          add one                            [n, 1]
     $         swap top two values                [1, n]
      1-       subtract one                       [1, n-1]
        :      duplicate top value                [1, n-1, n-1]
         ?!;   if n is 0, end                     [1, n-1]
            $  swap top two stack values          [n-1, 1]
             ! skip next instruction (0)

For both simply place n on the stack and the result will be outputted.

\$\endgroup\$
1
\$\begingroup\$

SmileBASIC, 31 bytes

INPUT N
FOR I=.TO N?CHR$(I)NEXT

. is read as 0.0, and I could have just used 0 in this case, but . looks cooler.

\$\endgroup\$
1
\$\begingroup\$

PHP, 35 34 bytes

<?=join(range(a^a,chr($argv[1])));

yup. PHP can create a range of characters.

Takes argument from command line. Save to file, execute.

\$\endgroup\$
1
\$\begingroup\$

J, 8 bytes

f=:{.&a.

Explanation:

f=:{.&a.
f=:      define a function f
      a. the ascii sequence
     &   attach it to the next operator
   {.    take the first n items of
         you'll notice I don't say how many,
         that's because in J you can leave blanks and the interpreter fills them in
\$\endgroup\$
2
  • \$\begingroup\$ I trust that you did something, but I don't see what changed. \$\endgroup\$
    – Bijan
    Commented Mar 15, 2017 at 13:31
  • \$\begingroup\$ Riley's edit formatted the header by prefixing # so it would be styled as a header (larger font, bold). \$\endgroup\$
    – DLosc
    Commented Mar 15, 2017 at 22:08
1
\$\begingroup\$

evil, 10 bytes

I've been playing around with evil lately, and this is my first PPCG submission (albeit 2.5 years late). I find it a fun esolang to use partially because it seems nobody uses it!

ramlwalusb

Explanation

r   // Store input character to Accumulator as byte
a   // Since we are writing then adding, add 1 to Accumulator
m   // Drop a loop marker
l   // Swap Wheel and Accumulator
w   // Output Accumulator
a   // Increment Accumulator
l   // Swap Wheel and Accumulator
u   // Decrement Accumulator
sb  // Go back to m if A != 0

evil is also an easy language to write an interpreter for. I think there's a javascript one floating around somewhere, but I ended up just writing my own.

EDIT: Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ Cool answer! Welcome to the site! \$\endgroup\$
    – DJMcMayhem
    Commented Mar 15, 2017 at 18:47
1
\$\begingroup\$

Jelly, 2 bytes

ḶỌ

Try it online!

According to current reference implementation as of time of posting.


Jelly, 3 bytes

‘ḶỌ

Try it online!

Inclusive. Reference implementation is exclusive.

\$\endgroup\$
1
1
\$\begingroup\$

R, 24 bytes

cat(intToUtf8(1:scan()))

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Tcl, 47 bytes

set i 0
time {puts [format %c $i];incr i} $argv

Try it online!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Making the user set n is not valid \$\endgroup\$
    – ASCII-only
    Commented May 9, 2018 at 22:10
  • \$\begingroup\$ @ASCII-only: I am in the process of reviewing my older answers. Thanks for pointing out \$\endgroup\$
    – sergiol
    Commented May 9, 2018 at 23:54
1
\$\begingroup\$

Excel VBA, 26 bytes

An anonymous VBE immediate window function that takes input from cell [A1]

For i=1To[A1]:?Chr(i):Next
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.