title: What's the file extension?

text:
# Question
Title: What's the file extension?
Your challenge is to find the file extension of a provided filename:

```
hi.txt -> txt or .txt
carrot.meme -> meme or .meme
lol (undefined behavior)
what..is..this..file -> file or .file
.bashrc -> bashrc or .bashrc
T00M@n3KaPZ.h0wC[]h -> h0wC[]h or .h0wC[]h
agent.000 -> 000 or .000

```

**You must get the text from the last `.` or after the last `.` to the end of the string.** The first capturing group match of the regular expression `/\.([^.]+)$/` works, and so does splitting the input on `.`s and returning the last one.

The file name will always contain at least one `.`, but it may contain multiple `.`. (see examples)

The input will always match `^[.a-zA-Z0-9^!\[\]{}@$%+=]+$`.

# Answer
> 16 votes
# Retina, 5 bytes

```
.*\.

```

Replaces everything and a dot with nothing at all.

Try it online!

# Answer
> 11 votes
## JavaScript (ES6), 19 bytes

Returns the full filename when there's no file extension. I suppose this is an acceptable *undefined behavior*.

```
let f =

s=>s.split`.`.pop()

console.log(f("hi.txt"))               // -> txt
console.log(f("carrot.meme"))          // -> meme
console.log(f("lol"))                  // -> undefined behavior
console.log(f("what..is..this..file")) // -> file
console.log(f("T00M@n3KaPZ.h0wC[]h")) // -> h0wC[]h
console.log(f(".bashrc")) // -> bashrc
```

# Answer
> 10 votes
# POSIX Shell, 13

```
echo ${1##*.}

```

Try it online.

# Answer
> 10 votes
## Mathematica, 13 22 bytes

*Edit: Not sure how I missed the `".bashrc"` test case. Thanks to Artyer for keeping me honest.*

```
FileExtension["a"<>#]&

```

If the input matches `\.[^.]+`, then `FileExtension` just returns the empty string, so we prepend the letter `a`. In any other case, prepending `a` doesn't affect output of `FileExtension`.

# Answer
> 8 votes
# c function, 21

* 1 byte saved thanks to @Dennis.
* 3 bytes saved thanks to @JohanduToit.
* 2 bytes saved thanks to @Neil.
* 1 byte saved thanks to @algmyr.

```
f(s){s=rindex(s,46);}

```

Try it online.

# Answer
> 6 votes
# 05AB1E, 4 bytes

```
'.¡¤

```

Try it online! or Try All Tests

```
'.   # Push '.'
  ¡  # Split on occurrences of '.'
   ¤ # Tail

```

# Answer
> 6 votes
# Japt, 3 bytes

2 bytes of code, +1 for the `h` flag.

```
q.

```

### Explanation:

```
q.       Split the input by `.`
   -h    Return the last item

```

Try it online!

# Answer
> 4 votes
# PHP, 21 Bytes

```
<?=pathinfo($argn,4);

```

Try it online!

is a shorter expression for

```
<?=pathinfo($argn)[extension];

```

pathinfo

# PHP, 27 Bytes

```
<?=end(explode(".",$argn));

```

explode

Try it online!

## PHP \<7.0, 26 Bytes

```
<?=end(split("\.",$argn));

```

deprecated split

# Answer
> 4 votes
# Neo4j Cypher, 24 bytes

```
return split($i,".")[-1]

```

Input is in a param (`i`), probably the only way for cypher to take input. Pretty straightforward. Cypher has never been used on PPCG before

# Answer
> 4 votes
# Taxi, 1397 bytes

```
Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to Chop Suey.Go to Chop Suey:n 1 r 1 l 4 r 1 l.[a]Pickup a passenger going to Narrow Path Park.Go to Narrow Path Park:n 1 l 1 r 1 l.Go to Chop Suey:e 1 r 1 l 1 r.Switch to plan "b" if no one is waiting.Switch to plan "a".[b]Go to The Babelfishery:n 1 l 1 l.[c]Go to Fueler Up:n.Go to Joyless Park:n 2 r.Go to Narrow Path Park:w 1 r 3 l.Pickup a passenger going to Cyclone.Go to Cyclone:w 1 l 1 r 2 l.Pickup a passenger going to Crime Lab.Pickup a passenger going to Joyless Park.'.' is waiting at Writer's Depot.Go to Writer's Depot:s.Pickup a passenger going to Crime Lab.Go to Crime Lab:n 1 r 2 r 2 l.Switch to plan "c" if no one is waiting.Go to Narrow Path Park:n 5 l.[d]Pickup a passenger going to Chop Suey.Go to Chop Suey:e 1 r 1 l 1 r.Go to Narrow Path Park:n 1 l 1 r 1 l.Switch to plan "e" if no one is waiting.Switch to plan "d".[e]Go to Joyless Park:e 1 r 3 l.Switch to plan "f" if no one is waiting.Pickup a passenger going to Narrow Path Park.Go to Fueler Up:w 1 l.Go to Narrow Path Park:n 4 l.Switch to plan "e".[f]Go to Narrow Path Park:w 1 r 3 l.[g]Switch to plan "h" if no one is waiting.Pickup a passenger going to KonKat's.Go to KonKat's:e 1 r.Pickup a passenger going to KonKat's.Go to Narrow Path Park:n 2 l.Switch to plan "g".[h]Go to KonKat's:e 1 r.Pickup a passenger going to Post Office.Go to Post Office:s 3 r 1 l.

```

Try it online!

Taxi doesn't have a reverse function so this ballooned pretty quickly. The logic is:

1. Break the string into characters
2. Reverse the array
3. Iterate through each until a period is found, storing each in a FIFO array
4. Empty the array (because there's only one LIFO array available)
5. Dump the FIFO array into the LIFO array
6. Concatenate the LIFO array and output

# Answer
> 3 votes
# , ~~5~~, 3 bytes

Since more of this answer is unprintable than printable, here is a hexdump:

```
00000000: cd81 ae                                  ...

```

Try it online!

This uses Jan Dvorak's algorithm, it just happens to be a more efficient encoding of it.

Explanation:

```
Í       " Remove all occurrences of:
 0x81   "   Anything (greedy)
     ®  "   Followed by a dot

```

Old solution:

```
$T.d|

```

# Answer
> 3 votes
# GNU Make, 12 bytes

```
$(suffix $1)

```

Not using a builtin, 27 bytes:

```
$(lastword $(subst ., ,$1))

```

# Answer
> 3 votes
## Batch, 10 bytes

```
@echo %~x1

```

Strangely competitive for once.

# Answer
> 3 votes
# Vim, 5 bytes

```
$F.d0

```

Explanation: find last `.` in line, delete everything before it

Another, longer, but in my opinion still interesting approach with 9 bytes (notice the trailing new line)

```
d/.*\./e

```

This one works similarly, 5 bytes (again, trailing new line):

```
d?\.

```

# Answer
> 3 votes
# C# (Visual C# Interactive Compiler), 22 bytes

```
s=>s.Split('.').Last()

```

Implicit `using System.Linq;` FTW!

Try it online!

# Answer
> 3 votes
# PowerShell, ~~34~~ 26 bytes

-8 bytes thanks to @mazzy

```
(Read-Host).Split('.')[-1]

```

Takes input from STDIN. Actually managed to golf it down shorter than the built-in.

# PowerShell, 20 bytes

```
($args-split'.')[-1]

```

Takes input from commandline arguments. Big thanks to @mazzy again!

# PowerShell (with built-in), 36 bytes

```
[IO.Path]::GetExtension((Read-Host))

```

# Answer
> 3 votes
# Forth (gforth), 45 bytes

```
: f begin 1 -1 d+ s" ."search 0= until type ;

```

Try it online!

### Code Explanation

```
: f              \ start a new word definition
  begin          \ start an indefinite loop
    1 -1 d+      \ remove the first character from the string
    s" ."search  \ find the length and starting address of the first substring that starts with '.'
    0=           \ check if '.' was found in the string
  until          \ end the loop if not
  type           \ output the result
;                \ end the word definition

```

# Answer
> 3 votes
# Python 3, 29 bytes

```
print(input().split(".")[-1])

```

# Answer
> 3 votes
# Rust, 34 bytes

```
|p|p.extension().or(p.file_stem())

```

Usable as a `fn(&std::path::Path) -> Option<&std::ffi::OsStr>`.

Try it online!

# Answer
> 2 votes
# JS (ES6), ~~26~~ 25 bytes

```
x=>/\.([^.]+)$/.exec(x)[1]

```

-1 byte thanks to Shaggy

```
document.querySelector('pre').innerText = (x=>/\.([^.]+)$/.exec(x)[1])("example.txt")
```

```
<input oninput = "document.querySelector('pre').innerText = (x=>x.match(/\.([^.]+)$/)[1])(this.value)" value = "example.txt">
<pre></pre>
```

Alternate, 29 bytes:

```
x=>(y=x.split`.`)[y.length-1]

```

# Answer
> 2 votes
# JavaScript (ES6), ~~33~~ ~~31~~ 28 bytes

```
s=>s.slice(s.lastIndexOf`.`)

```

Spec change in comments removes the need for `+1`.

-3 bytes thanks to nderscore

# Answer
> 2 votes
# Jelly, 4 bytes

```
ṣ”.Ṫ

```

A monadic link taking the file name and returning the extension with no leading `.`.

**Try it online!**

### How?

Literally does what was asked...

```
ṣ”.Ṫ - Main link: list of characters, f
 ”.  - literal '.'
ṣ    - split f at occurrences of '.'
   Ṫ - tail (get the last chunk)

```

# Answer
> 2 votes
# sed, 8 bytes

```
s:.*\.::

```

Try it online!

# Answer
> 2 votes
# Go, 85 bytes

Go is... troublesome.

```
import(."fmt"
."os"
."strings")
func main(){s:=Split(Args[1],".");Print(s[len(s)-1])}

```

Try it online!

A sample of parentheses from the code:

```
()(){([])([()])}

```

# Answer
> 2 votes
# Javascript (ES5), 38 bytes

```
function(s){return s.split(".").pop()}

```

# Answer
> 2 votes
# Common Lisp, 57 bytes

```
(lambda(s)(#1=reverse(subseq #2=(#1# s)0(search"."#2#))))

```

Try it online (added some bytes to call this anonymous function and display returned string)

### Explanation

```
(#1=reverse ...)     ;reverse is now accessible with #1# - saves 1 byte. I
                     ;also need to reverse output of function inside to
                     ;get extension in correct order
#2=(#1# s)           ;reverse of input string is now accessible with #2#
(search"."#2#)       ;I take reversed string and search for "." to get position of
                     ;first instance of "." in string from the end of it
(subseq ... 0 ...)   ;get part of reversed string,
                     ;starting from first character and ending just
                     ;before first occurance of "."
                     ;this gives reversed extension

```

I get substring of reversed string, starting from 0, ending on this

# Answer
> 2 votes
# C#, ~~33~~ 41 bytes

```
a=>a.Split('.').Last();

```

Edit as suggested:

```
using System.Linq;a=>a.Split('.').Last();

```

# Answer
> 2 votes
# Java 8, ~~52~~ 27 bytes

```
s->s.replaceAll(".*\\.","")

```

Try it here.

Replace everything before the last dot (and the dot itself) with nothing.

This is shorter than using split (`s->s.split("\\.")[s.split("\\.").length-1];`) or substring (`s->s.substring(s.lastIndexOf('.'));`).

# Answer
> 2 votes
# Gema, 3 characters

```
*.=

```

Sample run:

```
bash-4.4$ gema '*.=' <<< 'what..is..this..file'
file

```

# Answer
> 2 votes
# MATL, ~~8~~ 7 bytes

```
46&YbO)

```

Try it at MATL Online!

**Explanation**

```
        % Implicitly grab input as string
46      % ASCII for '.'
&Yb     % Split the input string at the '.' characters
O)      % Retrieve just the last part
        % Implicitly print the result

```

# Answer
> 2 votes
# Awk, ~~14~~ 13 characters

(~~10~~ 9 characters code + 4 characters command line option.)

```
{$0=$NF}1

```

Thanks to:

* Robert Benson for spotting the unnecessary semicolon (-1 character)

Sample run:

```
bash-4.4$ awk -F. '{$0=$NF}1' <<< $'hi.txt\ncarrot.meme\nlol\nwhat..is..this..file\n.bashrc\nT00M@n3KaPZ.h0wC[]h'
txt
meme
lol
file
bashrc
h0wC[]h

```

# Answer
> 2 votes
# Lua, ~~53~~ 30 bytes

Replaces everything upto the last `.` with the empty string `''`.

Double parenthesis to select only the first return value of `gsub`.

Any golfing tips are welcome, I'm rusty in lua...

```
print(((...):gsub('.*%.','')))

```

Try it online!

# Answer
> 2 votes
# K (oK), 6 bytes

**Solution:**

```
*|"."\

```

Try it online!

**Examples:**

```
*|"."\"whats.up.txt"
"txt"
  *|"."\"T00M@n3KaPZ.h0wC[]h"
"h0wC[]h"

```

**Explanation:**

Split `\` the input on `"."`, reverse `|` this list, and then take the first `*` one. K is interpreted right-to-left:

```
*|"."\ / the solution
  "."\ / "." split (\),
 |     / reverse
*      / first

```

# Answer
> 2 votes
# JavaScript, 21 bytes

```
x=>x.split('.').pop()

```

**Explanation:**

This code takes `x.txt` and turns it into a array. The last element of the array is the file type. This code uses the `pop` function to remove the last element. In the process, the `pop` function returns the last element.

# Answer
> 2 votes
# Python 3, 46 bytes

*-8 bytes thanks to Wheat Wizard and Scrooble*

```
import sys
print(sys.argv[1].split('.')[-1])

```

EDIT: I fixed the code, and the filename is a command-line argument

# Answer
> 2 votes
# FORTRAN 90, 87 bytes

```
CHARACTER(99)F,L
READ*,F;DO I=1,LEN(F)
IF(F(I:I)=='.')L=F(I:LEN(F))
ENDDO
PRINT*,L
END

```

A shorter version in FORTRAN 90.

---

# FORTRAN 77, 137 bytes

```
      PROGRAMC;IMPLICITCHARACTER*99(F)
      READ*,F;DOI=LEN(F),1,-1;IF(F(I:I).EQ.'.')THEN
      PRINT*,F(I:LEN(F));EXIT;ENDIF;ENDDO;END

```

There is no space in `PROGRAM C`, nor in `IMPLICIT CHARACTER`. It works (!) in `gfortran`, but I'm not sure it works in others compilers. The program takes input from `stdin` and outputs the extension *with* the period. The total length of the file name is limited by 99.

# Answer
> 2 votes
# SmileBASIC, 45 bytes

```
INPUT S$@L
E$=POP(S$)+E$ON"."==E$[0]GOTO@L?E$

```

Outputs extension with the period.

# Answer
> 2 votes
# Kotlin, 17 bytes

```
split(".").last()

```

## Beautified

```
split(".").last()

```

## Test

```
data class Test(val input: String, val output: String)

val test = listOf(
        Test("hi.txt", "txt"),
        Test("carrot.meme", "meme"),
        Test("what..is..this..file", "file"),
        Test(".bashrc", "bashrc"),
        Test("T00M@n3KaPZ.h0wC[]h", "h0wC[]h"),
        Test("agent.000", "000")
)

fun String.f() =
split(".").last()

fun main(args: Array<String>) {
    for ((i, o) in test) {
        if (o != i.f()) {
            throw AssertionError()
        }
    }
}

```

## TIO

TryItOnline

# Answer
> 2 votes
# , 4 bytes

```
òdt.

```

Try it online!

Recursively delete everything up to, but not including the next `.`

# Answer
> 2 votes
## C++, 73 bytes

I'm a bit surprised that no one tried C++, since it's an easy one :

```
#include<string>
auto e=[](std::string s){return s.substr(s.rfind(46));};

```

And the code to test ( may have to `iostream`, `initializer_list`, and `exception` ) :

```
std::initializer_list<std::string> test{
    "hi.txt", // .txt
    "carrot.meme", // .meme
    "lol", // invalid string position
    "what..is..this..file", // .file
    ".bashrc", // .bashrc
    "T00M@n3KaPZ.h0wC[]h", // .h0wC[]h
    "agent.000" // .000
};

for (const auto& a : test) {
    try {
        std::cout << e(a) << '\n';
    }
    catch (std::out_of_range& r) {
        std::cout << "out of range exception : " << r.what() << '\n';
    }
}

```

And, as you may expect, like compilers, if there's undefined behavior, there's no undefined behavior. If there's no file extension, the function will throw a `std::out_of_range` exception, as said in cppreference

# Answer
> 2 votes
# Turing Machine But Way Worse, ~~1315~~ 1287 bytes

```
0 0 0 1 1 0 0
1 0 1 1 8 0 0
0 1 0 1 2 0 0
1 1 1 1 9 0 0
0 2 0 1 3 0 0
1 2 1 1 a 0 0
0 3 0 1 4 0 0
1 3 1 1 b 0 0
0 4 0 1 5 0 0
1 4 1 1 c 0 0
0 5 0 1 6 0 0
1 5 1 1 d 0 0
0 6 0 1 7 0 0
1 6 1 1 e 0 0
0 7 0 1 f 0 0
1 7 1 1 0 0 0
0 8 0 1 9 0 0
1 8 1 1 9 0 0
0 9 0 1 a 0 0
1 9 1 1 a 0 0
0 a 0 1 b 0 0
1 a 1 1 b 0 0
0 b 0 1 c 0 0
1 b 1 1 c 0 0
0 c 0 1 d 0 0
1 c 1 1 d 0 0
0 d 0 1 e 0 0
1 d 1 1 e 0 0
0 e 0 1 0 0 0
1 e 1 1 0 0 0
0 f 0 0 g 0 0
1 f 1 0 g 0 0
0 g 0 0 h 0 0
1 g 1 0 p 0 0
0 h 0 0 q 0 0
1 h 1 0 i 0 0
0 i 0 0 r 0 0
1 i 1 0 j 0 0
0 j 0 0 s 0 0
1 j 1 0 k 0 0
0 k 0 0 l 0 0
1 k 1 0 t 0 0
0 l 0 0 u 0 0
1 l 1 0 m 0 0
0 m 0 0 n 0 0
1 m 1 0 v 0 0
0 n 0 0 o 0 0
1 n 1 0 g 0 0
0 p 0 0 q 0 0
1 p 1 0 q 0 0
0 q 0 0 r 0 0
1 q 1 0 r 0 0
0 r 0 0 s 0 0
1 r 1 0 s 0 0
0 s 0 0 t 0 0
1 s 1 0 t 0 0
0 t 0 0 u 0 0
1 t 1 0 u 0 0
0 u 0 0 f 0 0
1 u 1 0 f 0 0
0 o 0 1 w 0 0
1 o 1 1 w 0 0
0 w 0 1 x 0 0
1 w 1 1 E 0 0
0 x 0 1 y 0 0
1 x 1 1 F 0 0
0 y 0 1 z 0 0
1 y 1 1 G 0 0
0 z 0 1 A 0 0
1 z 1 1 H 0 0
0 A 0 1 B 0 0
1 A 1 1 I 0 0
0 B 0 1 C 0 0
1 B 1 1 J 0 0
0 C 0 1 D 0 0
1 C 1 1 K 0 0
0 D 0 1 D 0 1
1 D 1 1 w 1 0
0 E 0 1 F 0 0
1 E 1 1 F 0 0
0 F 0 1 G 0 0
1 F 1 1 G 0 0
0 G 0 1 H 0 0
1 G 1 1 H 0 0
0 H 0 1 I 0 0
1 H 1 1 I 0 0
0 I 0 1 J 0 0
1 I 1 1 J 0 0
0 J 0 1 K 0 0
1 J 1 1 K 0 0
0 K 0 1 w 1 0
1 K 1 1 w 1 0

```

Try it online!

Wow, this is big.

# Answer
> 2 votes
# Befunge-98 (FBBI), 50 bytes

```
{v
 >~:a`!#v_
--2*86:$<:u-10_v#
02-u0}>:#,_@   >00

```

Try it online!

Puts string onto stack, then iterates through it in reverse, putting each new character onto new stack. Once a `.` is encountered, discard original stack and output new stack in `0gnirts` format.

# Answer
> 2 votes
# 33 v1.0, 13 bytes

*The behaviour of the `y` operator was changed in v1.1, so this program no longer works*

Gets the file name passed as an argument and prints the extension (without leading '.') to standard output.

```
1bt'.'ywmcbtp

```

Explanation:

```
1b            (Gets the second item in argv, the filename input)
  t'.'y       (Splits that by '.')
       wmcb   (Gets the last element in the list)
           tp (Prints to standard output)

```

# Answer
> 2 votes
# brainfuck, 45 bytes

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

```

Try it online!

# Answer
> 2 votes
## Setanta, ~~66~~ 34 bytes

```
gniomh(s){toradh roinn@s(".")[-1]}

```

Try it here!

# Answer
> 2 votes
# Arn, 6 bytes

```
Ê^!⁺╔d

```

Try it!

# Explained

Unpacked: `:!".":}`

```
    _ Variable initialized to STDIN; implied
  :! Split on
    "." String containing a period
:} Tail

```

# Answer
> 2 votes
## APL (Dyalog Unicode), 10 bytes (SBCS)

```
⊃∘⌽'.'∘≠⊆⊢

```

-7 bytes after Bubbler's suggestion.

Try it online!

## APL (Dyalog Unicode), 17 bytes (SBCS)

```
⊃⌽'.'(1↓¨,⊂⍨⊣=,)⍞

```

### Explanation

```
⊃⌽'.'(1↓¨,⊂⍨⊣=,)⍞
                ⍞ string input
            ⊣=,)  get characters, evaluate if they are equal to the left arg '.'
         ,⊂⍨      enclose each part after a dot
  '.'(1↓¨         drop each dot in the strings
 ⌽                reverse the split string array
⊃                 take the first value

```

Try it online!

# Answer
> 2 votes
**Python3 (32 bytes)**

```
f=input()
print(f[f.rfind('.'):])

```

Try it online!

# Answer
> 2 votes
# 8086 Assembly (NASM) + DOS, 262 bytes source, 50 bytes assembled

I'm pretty new to assembly, but I thought I'd give this a try. This is a full DOS program, not just a snippet.

```
section .bss
b resb 256
org 256
section .text
mov byte[b],254
mov ah,10
mov dx,b
int 33
mov bh,0
mov bl,[b+1]
add bx,b+2
mov bp,bx
l:sub bx,1
cmp byte[bx],46
jne l
mov byte[bx],10
p:mov ah,2
mov dl,[bx]
int 33
add bx,1
cmp bx,bp
jb p
int 32

```

Essentially, it reads a line of text into a buffer, seeks the end, then seeks backwards until it reaches a `.`. Then it just prints the rest of the string from that point on. I wasn't able to use DOS's built-in print function, though, since that uses `$` as the end-of-string character, which the prompt says is a valid character for the extension itself.

Here is the hexdump of the assembled binary:

```
00000000  c6 06 34 01 fe 88 e4 ba  34 01 cd 21 b7 00 8a 1e
00000010  35 01 81 c3 36 01 89 dd  83 eb 01 80 3f 2e 75 f8
00000020  c6 07 0a b4 02 8a 17 cd  21 83 c3 01 39 eb 72 f3
00000030  cd 20

```

# Answer
> 2 votes
# Vyxal, 4 bytes

```
\.€t

```

Try it Online! (Test cases!)

Splits on spaces and outputs the tail.

# Answer
> 2 votes
# C (gcc), 50 bytes

```
p;char*f(char*s){for(;*s;)p=*s++^46?p:s;return p;}

```

Try it online!

# C (gcc), 45 bytes skipping `return`

```
p;char*f(char*s){for(;*s;)p=*s++^46?p:s;s=p;}

```

Try it online!

# C (gcc), 24 bytes by ceilingcat

```
#define f(s)rindex(s,46)

```

Try it online!

# Answer
> 1 votes
# Python 2, 25 bytes

```
lambda s:s.split('.')[-1]

```

Try it online!

# Answer
> 1 votes
# Brain-Flak, 84 bytes

Includes +2 for `-rc`

```
(()){{}([((((()()()){}())()){}{}){}]({}<>)<>)({()(<{}>)}{})}{}{{}}<>{}{({}<>)<>}<>

```

Try it online!

```
# Push 1 to start the loop
(())

# Start loop
{{}

  # If TOS == 46 i.e. '.'
  ([((((()()()){}())()){}{}){}]({}<>)<>)({()(<{}>)}{})
  # ^------------------------^ ^-------^
  #           This is 46         Also, copy TOS to other stack

# End loop after the first '.'
}{}

# Delete everything from this stack
{{}}

# Delete the '.' that got copied
<>{}

# Copy everything back to reverse it to the correct order
{({}<>)<>}<>

```

# Answer
> 1 votes
# Japt, ~~6~~ 5 bytes

```
q'. o

```

Try it online!

# Explanation

```
 q'. o
Uq'. o
Uq'.    # Split the input at "."
     o # Return the last item

```

# Answer
> 1 votes
# Charcoal, ~~6~~ 4 bytes

-2 bytes thanks to Erik the Outgolfer

```
⊟⪪Ｓ.

```

Try it online!

## Explanation

```
⊟      Pop
  ⪪ .  Split on "."
   Ｓ  Next input as string
       Implicit print of value

```

# Answer
> 1 votes
# jq, ~~15~~ 14 characters

(~~11~~ 10 characters code + 4 characters command line options.)

```
./"."|last

```

Sample run:

```
bash-4.4$ jq -Rr './"."|last' <<< 'what..is..this..file'
file

```

On-line test

# Answer
> 1 votes
# Octave, 24 bytes

```
@(x)strsplit(x,'.'){end}

```

Creates an anonymous function named `ans` which can accept a string as input

Online Demo

# Answer
> 1 votes
# C#, ~~47~~ ~~34~~ 27 bytes

```
System.IO.Path.GetExtension

```

*Saved 6 bytes thanks to @totallyhuman.*

Try it online!

# Answer
> 1 votes
# Pyth, 5 bytes

```
ecz\.

```

try it here

# Answer
> 1 votes
# REXX 53

```
parse value reverse(arg(1)) with e "."
say reverse(e)

```

# Answer
> 1 votes
# C#, 35 bytes

```
s=>s.Substring(s.LastIndexOf("."));

```

Try it online!

# Answer
> 1 votes
## Haskell, ~~32~~ ~~30~~ 29 bytes

*-1 byte thanks to Laikoni*

```
r=reverse
r.fst.span(/='.').r

```

self-explanatory

# Answer
> 1 votes
# C (gcc), ~~77~~ ~~60~~ 52 bytes

```
char*f(char*s){for(s+=strlen(s);*--s-46;);return s;}

```

Try it online!

-17 bytes from Jonathan Frech

-8 bytes by removing `i` and doing arithmetic on `s` directly

Ungolfed (same strategy):

```
char *extension(char *original) {
    original = original + strlen(original);
    while(original[0] != '.') --original;
    return original;
}

```

# Answer
> 1 votes
# Cheddar, 16 bytes

```
@.sub(/.*\./,"")

```

simple regex solution. Alternative solution using split:

```
@.split('.')[-1]

```

# Answer
> 1 votes
# Ruby, 16 bytes

```
->s{s[/[^.]+$/]}

```

Try it online!

# Answer
> 1 votes
# Ohm v2, 5 bytes

```
I..ï⁾

```

Try it online!

# Answer
> 1 votes
## Perl 5, 8 bytes

**7 bytes code + 1 for `-p`.**

```
s;.*\.;

```

Try it online!

# Answer
> 1 votes
# Excel, 58 bytes

```
=TRIM(RIGHT(SUBSTITUTE(A1,".",REPT(" ",LEN(A1))),LEN(A1)))

```

# Answer
> 1 votes
# Excel VBA, 29 bytes

An anonymous VBE immediate window function that takes input via cell `[A1]` and outputs to the console. Return string is of the form `.Extension`.

```
?Mid([A1],InStrRev([A1],"."))

```

# Answer
> 1 votes
# Yabasic, 34 bytes

A answer

Takes input as a string from STDIN, and outputs of the form `.Extension` to STDOUT.

```
Input""s$
?Mid$(s$,RInStr(s$,"."))

```

Try it online!

# Answer
> 1 votes
# Google Sheets, 25 bytes

An anonymous worksheet function that takes input from cell `A1` and outputs the detected file extension of the form `Extension` to the calling cell.

```
=RegexExtract(A1,"[^\.]+$

```

# Answer
> 1 votes
## \>\<\>, 50 bytes

```
i:0( ?v
v[:<2~<
r  ^]+1r<
>:"."=?v^
v?l<r~r<;
>o ^

```

Try it online!

# Answer
> 1 votes
# ActionScript 2.0, 42 bytes

```
function a(b){trace(b.split(".").pop());};

```

Technically the ;s aren't required for it to *compile*, at least in JPEXS, but it's good practice. Call:

```
a("a.b");

```

(traces "b")

# Answer
> 1 votes
# CJam, 6 bytes

```
q'./W=

```

Try it online!

```
        Print
    W     the last
     =    element
   /      of the result of splitting
q         the input
 '.       on the character '.'

```

# Answer
> 1 votes
# Add++, 9 bytes

```
L,"."$tbU

```

Try it online!

# Answer
> 1 votes
# Aceto, 6 bytes

```
r'.:Qp

```

Try it online!

```
r       grabs input as string
 '.     literal period
   :    split string on period
    Q   grap bottom item
     p  print it

```

# Answer
> 1 votes
# \>\<\>, 18 bytes

```
i:0(6$.:"."=?]
ro|

```

Try it online!

### How It Works:

```
i:(6$.  Jump to the second line if out of input
      :"."=  Else check if the character is a .
           ?[ And create a new stack if it is
              Loop back to the beginning of the line
If it is end of input
ro|  Reverse the current stack once and output, erroring on the EOF (-1)

```

# Answer
> 1 votes
# Stax, 4 bytes

```
'./H

```

Run and debug online!

## Explanation

Split on `.`, take last part.

# Answer
> 1 votes
# T-SQL, 48 bytes

```
SELECT RIGHT(F,CHARINDEX('.',REVERSE(F))) FROM T

```

SQL Fiddle

# Answer
> 1 votes
# SNOBOL4 (CSNOBOL4), 46 bytes

```
	I =INPUT
S	I '.' REM . I	:S(S)
	OUTPUT =I
END

```

Try it online!

Takes the input, then repeatedly replaces it with all the text following the first `.` until no `.`s remain, then outputs the value.

# Answer
> 1 votes
# Funky, 26 bytes

```
s=>(k=s::split".")[(#k)-1]

```

Try it online!

# Answer
> 1 votes
# Jotlin, 17 bytes

```
split(".").last()

```

Full file:

```
data class Test(val input: String, val output: String)

val test = listOf(
        Test("hi.txt", "txt"),
        Test("carrot.meme", "meme"),
        Test("what..is..this..file", "file"),
        Test(".bashrc", "bashrc"),
        Test("T00M@n3KaPZ.h0wC[]h", "h0wC[]h"),
        Test("agent.000", "000")
)

fun String.f() = split(".").last()

for ((i, o) in test) {
    if (o != i.f()) {
        throw AssertionError()
    }
}

```

# Answer
> 1 votes
# , ~~40~~ 26 bytes

-14 bytes thanks to J.Doe

```
sub("^.*[.]","",scan(,""))

```

Try it online!

# Answer
> 1 votes
## MBASIC, 129 bytes

```
1 INPUT F$:F=INSTR(F$,"."):IF F=0 THEN END
2 FOR I=LEN(F$) TO 1 STEP -1:P$=MID$(F$,I,1):O$=P$+O$:IF P$="." THEN PRINT O$:END
3 NEXT

```

**Explanation**

Get a filename. If it doesn't contain a period, bail out. Otherwise, collect letters from right to left to build an output string. When we see a period, print the string.

**Output**

```
? hi.txt
.txt

? .bashrc
.bashrc

? T00M@n3KaPZ.h0wC[]h
.h0wC[]h

```

# Answer
> 1 votes
# Red 9 bytes

```
Suffix? f

```

Assumes file is is in word 'f

# Answer
> 1 votes
# Pepe, 48 bytes

```
rEeeEeEEEeREEeREEEerEEREEEEEEEreererEEEEeEeereee

```

Try it online!

# Answer
> 1 votes
## Emacs, 6 bytes

The cursor needs to be at the start of the line containing the string.

This will delete the entire line if there's no extension.

```
C-<SPC> C-e C-r . <RET> <BACKSPACE>

```

Explanation:

```
C-<SPC>      start a selection
C-e          go to the end of the line
C-r . <RET>  search for "." backward
<BACKSPACE>  delete the selected text (which should be the text before the last ".")

```

# Answer
> 1 votes
# Pushy, 13 bytes

```
K46-$v;F@46+"

```

**Try it online!**

```
               \ Implicit: string on stack as character codes
K46-           \ Subtract 46 from each code point, mapping '.' to 0
    $v;        \ While the top of stack is non-zero, move to auxiliary stack
       F       \ Copy auxiliary stack onto main stack
        @      \ Reverse (to obtain original order)
         46+   \ Add 46 (to obtain original characters)
            "  \ Print as a string.

```

# Answer
> 1 votes
# Brain-Flak, 76 bytes

```
{((((([()()()]){}){}){}()){}{}<>)<>}<>{({}(((()()()()()){}()){}()){}<>)<>}<>

```

Try it online!

Explanation:

```
{          loop over stack
  (                            push
    (((([()()()]){}){}){}()){} -46
  {}                           plus the top of the stack
  <>)                          to the other side
<>}        retuen for more

<>      on the other side...

{       loop until 0
  (                             push
     {}                         the top of the stack
     (((()()()()()){}()){}()){} +46
  <>)                           to the first side
<>}       return for more

<> print the first side

```

6 bytes less than the other Brain-Flack solution.

# Answer
> 1 votes
# Pip, 8 bytes

```
@R:a^"."

```

Try It Online!

-2 from emanresu A.

# Answer
> 1 votes
# Keg, `-hd`, 4 bytes

```
\./÷

```

Try it online!

Splits on dots, and prints the last element.

# Answer
> 1 votes
# sed, 14 bytes

```
:l
s/.\././
tl

```

Try it online!

Just repeatedly removes the character before a `.` until there's none left.

# Answer
> 1 votes
# Factor, 14 bytes

```
file-extension

```

Try it online!

# Answer
> 1 votes
# Arturo, 24 bytes

```
$[s]->last split.by:"."s

```

Try it

# Answer
> 1 votes
# Python 3, 25 bytes

```
lambda f:f.split('.')[-1]

```

Everyone probably knows this works, so I'm not gonna put a TIO link.

# Answer
> 1 votes
# Raku, 12 bytes

```
m/.<-[.]>*$/

```

14 to make it a callable block:

```
{m/.<-[.]>*$/}

```

Try it online!

# Answer
> 1 votes
# Zsh, 7 bytes

```
<<<$1:e

```

Try it online!

# Answer
> 1 votes
# Thunno 2 `t`, 3 bytes

```
'./

```

Attempt This Online!

#### Explanation

```
'./  # Implicit input
  /  # Split the input on
'.   # The "." character
     # Implicit output of last item

```

# Answer
> 0 votes
# Groovy, 37 bytes

```
{it.substring(it.lastIndexOf(".")+1)}

```

Try it online!

# Answer
> 0 votes
# Ruby, 21 bytes

```
->f{f.split('.')[-1]}

```

Try it online!

# **12 bytes**

```
File.extname

```

# Answer
> 0 votes
# Tcl, 21 bytes

```
puts [file ext $argv]

```

Try it online!

# Answer
> 0 votes
# Julia, 22 bytes

```
g(n)=split(n,'.')[end]

```

# Answer
> 0 votes
# Perl 6, 11 bytes

```
{m/\.\w+$/}

```

Try it online!

---
Tags: code-golf, string
---


title: Print the ASCII table

text:
# Question
Title: 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.

# Answer
# 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.
> 19 votes

# Answer
# brainfuck - ~~169~~ ~~146~~ 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

```
> 26 votes

# Answer
## Pyth, 4 bytes

```
VQCN

```

Basically a translation of the Python 3 program:

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

```
> 12 votes

# Answer
# 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;
};

BefungeBoard.prototype.advance = function () {
    this.pointer = this.nextPosition();
    if (this.onAdvance) {
        this.onAdvance.call(null, this.pointer);
    }
};

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();
    this.board.advance();
};

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()) == ' ') {
                this.board.advance();
            }
            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, '&').replace(/</g, '<').replace(/>/g, '>');
        }

        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>
```
> 11 votes

# Answer
# Java, ~~151~~ ~~128~~ ~~77~~ ~~62~~ 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.
> 8 votes

# Answer
## APL,5

```
⎕UCS⍳

```

Example usage:

```
⎕UCS⍳256

```
> 7 votes

# Answer
# JavaScript, ES6 - ~~52~~ ~~58~~ ~~56~~ ~~53~~ ~~44~~ 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!
> 6 votes

# Answer
# 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'..])!!)

```
> 6 votes

# Answer
# Perl, 17 bytes

```
say chr for 0..$_

```
> 5 votes

# Answer
# 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!
> 4 votes

# Answer
# Bash+BSD common utilities, 9 bytes

```
jot -c $1

```

# GNU dc, 20 bytes

```
?sc_1[1+dPdlc>m]dsmx

```
> 4 votes

# Answer
# C, ~~31~~ ~~30~~ ~~28~~ 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
> 4 votes

# Answer
## CJam, 3

```
,:c

```

I assumed the argument to be the top stack element.

Example usage:

```
256,:c

ri,:c

```
> 3 votes

# Answer
# Ruby, 30 characters

```
puts (0..$*[0].to_i).map &:chr

```
> 3 votes

# Answer
## 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

```
> 3 votes

# Answer
# gs2, 2 bytes

```
V.

```

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

# Answer
## 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:

> ```
> ,
> [
>   <[<+> >++++++++++<-]
>   -[>-<-----]
>   >+++>,
> ]
> <[>]
> -<<[>.]
> >[>+.<-]
> ```
> 3 votes

# Answer
# √ å ı ¥ ® Ï Ø ¿ , 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

```
> 3 votes

# Answer
# Golfscript - 5

Thanks to @Dennis

```
~,''+

```
> 2 votes

# Answer
## Lua - ~~43~~ 41 Bytes

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

```
> 2 votes

# Answer
# 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-::0`j^                             ;
 ::-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                                               ;

```
> 2 votes

# Answer
## 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
> 2 votes

# Answer
# 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.
> 2 votes

# Answer
# 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.
> 2 votes

# Answer
# 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
> 2 votes

# Answer
# 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

```
> 2 votes

# Answer
# Perl - 29

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

```
> 2 votes

# Answer
# 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])]))

```
> 2 votes

# Answer
# 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)`
> 2 votes

# Answer
# 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
                                                                    10 and then adding all
                                                                    three

[>.+<-]                                                             Repeatedly prints the
                                                                    value of the adjacent
                                                                    cell and then adds one
                                                                    to it until it reaches
                                                                    the input value.

```
> 2 votes

# Answer
## Ruby - ~~35~~ 33 bytes

Please note that I can't Ruby at all:

```
$*[0].to_i.times{|i|puts i.chr()}

```
> 1 votes

# Answer
# PowerShell - 20

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

Usage:
56 | %{0..$_|%{[char]$_}}

```
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
# 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!
> 1 votes

# Answer
# Rebol - 35 34

```
for n 0 do input 1[prin to-char n]

```
> 1 votes

# Answer
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)
> 1 votes

# Answer
# 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 `str`ings, not `bytes`trings).

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.
> 1 votes

# Answer
# PHP - 47 bytes

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

```

Usage:

```
php ascii.php n

```
> 1 votes

# Answer
# LiveScript - 47

```
f=->alert String.fromCharCode.apply(,[0 to it])

```
> 1 votes

# Answer
# 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);

```
> 1 votes

# Answer
# F# - 66 characters

```
[<EntryPoint>]
let m a=
 for x in char 0..a.[0].[0]do printfn"%c"x
 0

```
> 1 votes

# Answer
## PowerShell, 20

```
[char[]](0.."$args")

```
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
# 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. :)*
> 1 votes

# Answer
# 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

```
> 1 votes

# Answer
## 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!
> 1 votes

# Answer
# Perl 6, ~~25~~ 22 bytes

```
put (^@*ARGS[0])».chr

```
> 1 votes

# Answer
## 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
> 1 votes

# Answer
# Japt, 7 bytes

```
Uo md q

```

Test it online!

### How it works

```
      // Implicit: U = input integer
Uo    // Create the range [0..U).
md    // Map each item X in this range to X.d().
      // If X is a number, this turns into the character with that char code.
q     // Join the array with the empty string.
      // Implicit: output last expression

```
> 1 votes

# Answer
## 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.
> 1 votes

# Answer
## Lua, 37 Bytes

```
a=...for i=1,a do print(a.char(i))end

```
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
# Pushy, 2 bytes

Input is given on the command line, `$ pushy asciitable.pshy 90`. Note that this will not work for numbers larger than 127.

```
X"

```

Explanation:

```
    \ Implicit: Input number on stack
X   \ Get range [0, n)
 "  \ Interpret as charcodes and print

```
> 1 votes

# Answer
## \>\<\>, 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.
> 1 votes

# Answer
# Tcl, 47 bytes

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

```

Try it online!
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
# 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

```
> 1 votes

# Answer
# 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!
> 1 votes

# Answer
# , 24 bytes

```
cat(intToUtf8(1:scan()))

```

Try it online!
> 1 votes

# Answer
# Excel VBA, 26 bytes

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

```
For i=1To[A1]:?Chr(i):Next

```
> 1 votes

# Answer
# Yabasic, 34 bytes

```
Input""n
For i=1To n
?Chr$(i)
Next

```

Try it online!
> 1 votes

# Answer
# Kotlin, 42 bytes

```
{n:Int->for(c in 0..n-1)print(c.toChar())}

```

Try it online!
> 1 votes

# Answer
# Check, 2 bytes

```
,o

```

Try it online!

Check has:

* Implicit input
* A range builtin
* A builtin to output a list of codepoints as characters
> 1 votes

# Answer
# Momema, 25 bytes

```
0*-8j0j+1-=*0-9*00+-1*0j1

```

Outputs the characters in reverse order. Try it online!

## Explanation

```
0   *-8     #            [0] = read num
j   0       #  label j0: goto j0
j   +1-=*0  #  label j1: goto j(1 - !![0])
-9  *0      #            print char [0]
0   +-1*0   #            [0] = 1 + [0]
j   1       #  label j2: goto j0

```
> 1 votes

# Answer
## Keg, 4 bytes (SBCS)

```
¿ï(,

```

TIO

Push input, output ASCII table.
> 1 votes

# Answer
# Snap!, 121 bytes

```
when gf clicked
set[a v]to(
ask[]and wait
for[i v]=(1)to[answer v]
set[a v]to join[a v]unicode[i v]as letter
end
say[a v]

```

Snap! is quite better than scratch, but I am having problem at the scratchblocks2 syntax because Snap! has some extra blocks.
> 1 votes

# Answer
# A0A0, 122 bytes

```
I0A3L0S1M4V0G0D1A0
G-1A0A0
A0C4G1G1A0
A0
A0G1G1G1V0P0S1A0
A0A1G-4G-4A0
G-4

A0A0
C3G1G1A0C3G1G1A0
A0G-6A0
A0A1G-3G-3A0
G-3

```

Works by creating a loop where one line counts how many iterations (from x to 0) have been done and the other line prints each character (from 0 to x). The first line is constructing during run-time based on the inputted number in the first line of the code.

```
L0 S1 M4 V# G0 D1 ; first line, the # indicates user number
L0                ; compares 0 to the inputted number
   S1             ; adds 1 to the comparison result
      M4          ; multiplies this result with 4
         V#       ; sets this result to the G0
            G0    ; jumps this result of lines below
               D1 ; subtract one from the inputted number

G1 G1 G1 V0 P0 S1 ; second line
G1 G1 G1          ; no-ops to align the instructions with the first line
         V0       ; the operand, sets the value of the next instruction
            P0    ; prints the value set by the operand
               S1 ; adds 1 to the operand

```

For the jumping, jumping by 4 (we hit the last number) will jump to an empty line, halting the program, while jumping by 8 (we're not finished yet) gets us into a loop below which jumps back up to the first loop.
> 1 votes

# Answer
# Stax, 1 byte

```
r

```

Run and debug it

Integer arrays are auto printed as strings.
> 1 votes

# Answer
# Japt `-P`, 2 bytes

```
od

```

Try it

```
od     :Implicit input of integer
o      :Range [0,input)
 d     :Get the character at each codepoint
       :Implicitly join & output

```
> 1 votes

# Answer
# Thunno 2 `B`, 1 byte

```
L

```

Attempt This Online!

### Thunno 2, 3 bytes

```
LCJ

```

Attempt This Online!

#### Explanation

```
L  # Implicit input
L  # Lowered range
   # B flag casts the list of ordinals
   # into a string of characters
   # Implicit output

```

```
LCJ  # Implicit input
L    # Lowered range
 C   # Cast to characters
  J  # Join into a string
     # Implicit output

```
> 1 votes

# Answer
## Haskell - ~~16~~ 22 characters

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

```

## Edit

Now printing the result

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

```
> 0 votes

# Answer
Lua

```
for i=0,255 do
    print(string.char(i))
end

```
> 0 votes

# Answer
# C, 31 bytes

```
i;f(n){for(;i<n;)putchar(i++);}

```

Use:

```
i;f(n){for(;i<n;)putchar(i++);}

int main(void)
{
    f(34);   //Call the function
    return 0;
}

```
> 0 votes

# Answer
## 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?
> 0 votes

# Answer
# 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
}

```
> 0 votes

# Answer
# **C#, 112 | 83 bytes**

Full program, 112 bytes:

```
class P{static void Main(string[]a){for(int i=0;i<int.Parse(a[0]);i++){System.Console.Write("{0}\n",(char)i);}}}

```

A function, 83 bytes:

```
static void f(int n){for(int i=0;i<n;i++){System.Console.Write("{0}\n",(char)i);}}}

```
> 0 votes

# Answer
# Microscript, 9 bytes

`i1{d1s}ah`

Or alternatively:

`i1cs1]fah`
> 0 votes

# Answer
### Excel VBA - 143

```
For i = 1 To 127
Cells(i, 1) = i
Cells(i, 2) = Evaluate("DEC2HEX(" & i & ")")
Cells(i, 3) = Evaluate("DEC2OCT(" & i & ")")
Cells(i, 4) = Chr(i)
Next

```
> 0 votes

# Answer
# K: 8 bytes

```
{10h$!x}

```

# Q: 11 bytes

```
{10h$til x}

```
> 0 votes

# Answer
# Gema, 43 characters

```
*=@set{i;0}@repeat{*;@int-char{$i}@incr{i}}

```

Sample run:

```
bash-4.3$ gema '*=@set{i;0}@repeat{*;@int-char{$i}@incr{i}}' <<< 96 | xxd
0000000: 0001 0203 0405 0607 0809 0a0b 0c0d 0e0f  ................
0000010: 1011 1213 1415 1617 1819 1a1b 1c1d 1e1f  ................
0000020: 2021 2223 2425 2627 2829 2a2b 2c2d 2e2f   !"#$%&'()*+,-./
0000030: 3031 3233 3435 3637 3839 3a3b 3c3d 3e3f  0123456789:;<=>?
0000040: 4041 4243 4445 4647 4849 4a4b 4c4d 4e4f  @ABCDEFGHIJKLMNO
0000050: 5051 5253 5455 5657 5859 5a5b 5c5d 5e5f  PQRSTUVWXYZ[\]^_

```
> 0 votes

# Answer
# Hassium, 45 Bytes

```
func a(n)for(x=0;x<n;print((x++).toChar())){}

```

Run and see expanded here
> 0 votes

# Answer
# Pylons, 9

```
0{d1+,i}c

```

How it works:

```
0     # Push 0 to the top of the stack.
{     # Start a for loop.
 d    # Duplicate the top of the stack.
  1   # Push 1 to the stack.
   +  # Add the top two elements of the stack.
 ,    # Switch to for loop iterators.
  i   # Get input
   }  # End for loop
c     # Print stack as joined array of chars and exit.

```
> 0 votes

# Answer
# Oracle SQL 11.2, 48 bytes

```
SELECT CHR(LEVEL)FROM DUAL CONNECT BY LEVEL<=:1;

```
> 0 votes

# Answer
# DUP, 21 bytes

```
[1+a:0[$1+$a;<][^,]#]

```

`Try it here!`

Anonymous lambda. Usage:

```
256[1+a:0[$1+$a;<][^,]#]!

```

# Explanation

```
[                     {start lambda}
 1+a:                 {inputnum is end of range (saved to a)}
     0                {0 is start of range}
      [       ][  ]#  {while loop}
       $1+$a;<        {dup, increment, check if top of stack < a}
                ^,    {if so, output char}
                    ] {end lambda}

```
> 0 votes

# Answer
# Java ~~76~~ ~~74~~ 70

Thanks to Mego for saving 4 bytes.

```
public void f(int x){for(int u=0;u<x;u++)System.out.println((char)u);}

```

Previous versions:

```
class f{public void f(int x){for(int u=0;u<x;u++)System.out.println((char)u);}}
class f{public f(int x){for(int u=0;u<x;u++)System.out.println((char)u);}}

```

The second version needs to be called by `new f(n);`

Feel free to give me ideas for making it even smaller.
> 0 votes

# Answer
## QBIC, 14 bytes, NC

```
:[a|?chr$(b-1)

```

Takes a number form the command line and loops from 1 to that number, feeding each iteration into `CHR$`.

Non-competing, QBIC was thought of a year after this challenge was posted.
> 0 votes

# Answer
## Perl 6, 9 bytes

```
(^*).chrs

```

The header and code alone are too short, so have this extra sentence.
> 0 votes

# Answer
# Java 8, 45 bytes

A lambda expression which takes an integer and prints the table to `STDOUT`. Golfing suggestions welcome!

```
x->{for(char i=0;i<x;System.out.print(i++));}

```

It's not clear whether OP wants `x` to be the last character printed, or the first character *not* printed. If it's the second, just change `i<x` to `i<=x` :)
> 0 votes

# Answer
# Python, 30 bytes

An unnamed lambda function which returns the result as a string.

```
lambda n:('%c'*n)%(*range(n),)

```

**Try it online!**

This uses the `printf`-style string formatting: when `'%c'` is formatted with an integer, it converts the integer to a character and displays that. So, we multiply the string by `n`, and format it with all values in `range(n)`.

# 29 bytes

If we want to be cheeky and return a list of characters instead of a string, we can get 1 byte shorter:

```
lambda n:[*map(chr,range(n))]

```

**Try it online!**
> 0 votes

# Answer
# QC 18 bytes

`'00901)01016010003`

```
'00 Read from stdin and store in memory at address 00
901 Print memory from address 01 until 0 is reached
)0101 Increment memory at 01 by 1
6010003 Jump to 03 if value at 01 and 00 are not equal

```

Edited because of invalid amount of bytes
> 0 votes

# Answer
## REXX, 28 bytes

```
say xrange('0'x,d2c(arg(1)))

```
> 0 votes

# Answer
# Sinclair ZX81 171 bytes for the listing (method 1):

```
 1 LET N$=""
 2 GOTO 2+(INKEY$<>"")
 3 LET A$=INKEY$
 4 IF A$=CHR$ 118 THEN GOTO 9
 5 IF CODE A$<28 OR CODE A$>37 THEN GOTO 2
 6 PRINT A$;
 7 LET N$=N$+A$
 8 GOTO 2
 9 LET N=VAL N$
10 IF N>255 THEN LET N=255
11 PRINT AT 0,0;
12 FOR I=0 TO N
13 PRINT CHR$ N;
14 NEXT I

```

This is using the `INKEY$` command to build a string of numbers, which is checked by comparing each input to the character range from 0 to 9 inclusing in line 5. Each character is stored in the `N$` variable and outputted to the screen. `CHR$ 118` is the ZX81 equivalent of a new line `"\r\n"` in PHP for instance.

There is a check to see if you have entered a valid range once you have pressed `NEW LINE` (0 to 255 inclusive) - as you can only enter numbers, the range is not going to be below zero.

Then there is a simple `FOR...NEXT` loop from line 12 to output the non-ASCII compatible character set. So I lose points because the ZX81 does not handle ASCII without some conversion tables.

Also, the ZX81 character set is incomplete to upper-case and inversed upper-case only; the remaining characters are either graphical symbols or they are ZX81 BASIC keywords, such as PI, INKEY$, PRINT etc... There is a much simpler method that I will post later, but is more prone to human error.

## Method 2, 34 bytes for the listing, no error checks and sanitizing inputs:

```
 1 INPUT N
 2 FOR I=0 TO N
 3 PRINT CHR$ I;
 4 NEXT I

```

Of course I'm sure that someone has already pointed out that true ASCII is 7 bit and the first 8 bit compatible ASCII set was PETSCII.
> 0 votes

# Answer
# Commodore 64/128

This solution uses `PETSCII` which is an 8-bit wide ASCII-compatible character set.

## Solution 1 - 42 BASIC bytes used (35 bytes for the listing)

```
0 printchr$(14);:fori=0to255:poke1024+i,i:next

```

## Solution 2 - 10 bytes assembled, ~72 bytes source code

```
* = 49152
lda #$00
tax
.loop
    sta $0400,x
    dex
    txa
bne loop
rts

```

The assembly is doing what the BASIC listing is doing (without switching the character set to business mode first), but is obviously many times quicker. As the 6502 (6510/85xx) processor has an 8-bit accumulator and \[8-bit\] registers, we start at zero and count down, so 0 - 1 is 0xff. Each character is stored in the screen RAM located at 0x0400 (1024) and `sta $0400,x` says `store the content of X to location $0400 + x`. The `bne loop` will `branch` back based on the zero flag, once that is set (i.e., `x=0x00`) it will drop out of the loop and return to BASIC with `rts`.

Once assembled, run with `sys 49152` \- this solution should work on the C64 and 128. It will work on other Commodore machines as long as you move the routine to a free area of RAM and relocate the starting point of the screen RAM from 1024.
> 0 votes

# Answer
# 05AB1E, 3 bytes

```
L<ç

```

Try it online!

```
L<ç  # full program
  ç  # convert...
     # (implicit) each element of...
L    # [1, 2, 3, ...,
     # ..., implicit input...
L    # ]...
     # (implicit) with each element...
 <   # decremented...
  ç  # to chars
     # implicit output

```
> 0 votes

# Answer
# C

I still get better, hopefully.

```
#include <stdio.h>
int main() {
    for(int i='a';i<='z';printf("%d\n",i),i++);
  return 0;
}

```
> 0 votes

# Answer
# Pxem, Filename: 19 bytes + Content: 0 bytes = 19 bytes.

Now the debut of lazypxem.min.posixism.

* Filename (escaped some): `._.c.w\001.-.c.c.a.s.p`
* Content is empty.

Try it online! The footer has `|od -vtu1` to be commented; uncomment it to inspect the exact output.
> 0 votes

# Answer
# Factor, 16 bytes

```
[ <iota> print ]

```

In modern versions of Factor, you can output sequences directly as strings. Here's a pic:

To get it to run on build 1525 (the one TIO uses), you'd have to convert the range to a string like this:

# Factor, 21 bytes

```
[ iota ""like print ]

```

Try it online!
> 0 votes

# Answer
# C (gcc), 27 bytes

```
f(c){c&&f(c-1),putchar(c);}

```

Try it online!

# C (MSVC), 25 bytes

```
f(c){c&&f(c-1),putch(c);}

```
> 0 votes

# Answer
# Ly, 7 bytes

```
n[:o,]o

```

Try it online!

This one, like at least one previous entry, prints the numbers from largest codepoint to 0, which wasn't disallowed in the rules as far as I can tell.

```
 n        - read the number of characters to print
  [   ]   - loop until the top of stack is 0
   :      - duplicate the top of stack
    o     - print it
     ,    - decrement the top of stack
       o  - print the x'00' entry

```
> 0 votes

# Answer
# Vyxal `s`, 2 bytes

```
ʁC

```

Try it Online!
> 0 votes

---
Tags: code-golf
---