28
\$\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\$
  • \$\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 Oct 28 '14 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 Oct 28 '14 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 Oct 28 '14 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\$ – FryAmTheEggman Oct 28 '14 at 12:59
  • 2
    \$\begingroup\$ nota [i for i in range(n)] is quite similar to range(n) \$\endgroup\$ – njzk2 Oct 28 '14 at 19:22

89 Answers 89

1
\$\begingroup\$

PowerShell - 20

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

Usage:
56 | %{0..$_|%{[char]$_}}
\$\endgroup\$
  • \$\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 Oct 30 '14 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\$
  • 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 Oct 28 '14 at 13:28
  • 2
    \$\begingroup\$ @Forlan07, not really an alias. p is equivalent to puts whatever.inspect. \$\endgroup\$ – manatwork Oct 28 '14 at 13:36
  • \$\begingroup\$ @manatwork OK, nice to know :-) \$\endgroup\$ – oopbase Oct 28 '14 at 13:39
  • \$\begingroup\$ This prints every character on a separate line. Shouldn't it be print? \$\endgroup\$ – nyuszika7h Oct 29 '14 at 13:48
  • \$\begingroup\$ Fixed and 3 bytes shorter: puts (0..$*[0]).map(&:chr)*'' \$\endgroup\$ – nyuszika7h Oct 29 '14 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\$
  • 7
    \$\begingroup\$ Posting multiple answers is perfectly fine. \$\endgroup\$ – Dennis Oct 28 '14 at 20:55
  • \$\begingroup\$ @Dennis is well aware of this. Just check all the questions he's answered \$\endgroup\$ – caird coinheringaahing Mar 15 '17 at 22:00
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\$
  • \$\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 Oct 29 '14 at 15:18
  • \$\begingroup\$ Actually, just lambda n:print(bytes(range(n+1))) works perfectly well. \$\endgroup\$ – Beta Decay Oct 29 '14 at 15:20
1
\$\begingroup\$

LiveScript - 47

f=->alert String.fromCharCode.apply(,[0 to it])
\$\endgroup\$
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\$
  • \$\begingroup\$ I think you can remove the PHP tag. JS answers typically don't include script tags, either. \$\endgroup\$ – Ingo Bürk Oct 30 '14 at 7:19
  • \$\begingroup\$ OK, ty. First post so not sure how it goes :) \$\endgroup\$ – Dexa Oct 30 '14 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\$ – nyuszika7h Oct 30 '14 at 19:12
  • \$\begingroup\$ @nyuszika7h Node doesn't support ES6 and yet ES6 answers don't include tags. \$\endgroup\$ – Ingo Bürk Oct 30 '14 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\$ – nyuszika7h Oct 30 '14 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
    \$\begingroup\$ The standard tips for casting to chars when golfing in MATLAB / Octave: @(n)[0:n,'']. =) Saves you a byte! \$\endgroup\$ – Stewie Griffin Jan 12 '16 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\$
  • \$\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\$ – Martin Ender Jun 10 '15 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 Jun 11 '15 at 8:46
  • \$\begingroup\$ I'm not very familiar with C#'s lambdas, but I think so. \$\endgroup\$ – Martin Ender Jun 11 '15 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\$
  • \$\begingroup\$ join does the same as implode and is 3 bytes shorter. \$\endgroup\$ – Titus Dec 14 '16 at 13:20
  • \$\begingroup\$ @Titus good catch, updated! \$\endgroup\$ – zamnuts Dec 15 '16 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\$
  • \$\begingroup\$ I trust that you did something, but I don't see what changed. \$\endgroup\$ – Bijan Mar 15 '17 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 Mar 15 '17 at 22:08
1
\$\begingroup\$

√ å ı ¥ ® Ï Ø ¿ , 3 bytes

Note: Non-competing as 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
\$\endgroup\$
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\$
  • \$\begingroup\$ Cool answer! Welcome to the site! \$\endgroup\$ – DJMcMayhem Mar 15 '17 at 18:47
0
\$\begingroup\$

Haskell - 16 22 characters

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

Edit

Now printing the result

print.(`take`['\0'..])
\$\endgroup\$
  • \$\begingroup\$ nice trick to get rid of a character \$\endgroup\$ – John Dvorak Oct 29 '14 at 9:32
  • \$\begingroup\$ This doesn't actually print the result. \$\endgroup\$ – nyuszika7h Oct 29 '14 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\$ – archaephyrryx Oct 29 '14 at 15:57
0
\$\begingroup\$

Lua

for i=0,255 do
    print(string.char(i))
end
\$\endgroup\$
  • 4
    \$\begingroup\$ This is code golf, so please include the byte count of your submission in the answer. Also, you don't need the line breaks. You can put all of this in one line like for i=0,255 do print(string.char(i)) end. \$\endgroup\$ – Martin Ender Dec 31 '14 at 19:19
  • \$\begingroup\$ This is not valid solution as it not handles input/parameter as required. \$\endgroup\$ – manatwork Jul 22 '16 at 9:27
0
\$\begingroup\$

PL/SQL 59

select chr(rownum)from dual connect by rownum<=&i

Didn't see a requirement that said output had to be a concatenated string, so this should work?

\$\endgroup\$
0
\$\begingroup\$

JavaScript, 65 bytes

First code golf, but here's my simple JavaScript implementation:

function f(n){for(i=1;i<n;)console.log(String.fromCharCode(i++))}

Not great but decent. ;)

Usage:

f(x) // x could be any number, but generally numbers
     // greater than 0 are better. ;)

The output is rather long so I'm not going to copy it but if you run it I think you'll get the idea. :P

Uncompressed:

function f(n) {
    for (i = 1; i < n;)
        console.log(String.fromCharCode(i++)); // by using i++ we increase
                                               // i right as we get it
}
\$\endgroup\$
  • \$\begingroup\$ Welcome to PPCG! I don't think you need those braces, and you do the i++ when call the function like ...fromCharCode(i++) and then leave the third section of the for statement empty. \$\endgroup\$ – Martin Ender Jun 10 '15 at 13:42
  • \$\begingroup\$ However, I just noticed that your answer isn't quite valid. You should write a function which takes 256 as a parameter. \$\endgroup\$ – Martin Ender Jun 10 '15 at 13:44
  • \$\begingroup\$ Also, I think you should start the loop at 0 rather than 1. \$\endgroup\$ – Peter Taylor Jun 10 '15 at 14:00
  • \$\begingroup\$ Ah, I'll update to fit what you guys have pointed out. :) \$\endgroup\$ – Florrie Jun 10 '15 at 15:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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