text:
Don't give me five!
Question :
You will be given the starting and ending integers of a sequence and should return the number of integers within it which do not contain the digit 5. The start and end numbers should be included!

Examples:
1,9 → 1,2,3,4,6,7,8,9 → Result 8
4,17 → 4,6,7,8,9,10,11,12,13,14,16,17 → Result 12
50,60 → 60 → Result 1
-59,-50 → → Result 0

The result may contain five.
The start number will always be smaller than the end number. Both numbers can be also negative!
I'm very curious for your solutions and the way you solve it. Maybe someone of you will find an easy pure mathematics solution.
Edit
This is a code-golf challenge, so the shortest code wins.

@betseq: That´s close; but this one has a variable range (and requires no modulo).

I'd recommend shortest code as winning criterion and the code-golf tag (I didn't even spot that it wasn't!). Also, you should probably should put a test case that spans 50 or 500; also maybe one that spans -50, and one that spans 0 would be a good idea.

@Qwerp-Derp: Add winning criteria.

@JonathanAllan : I will update examples.

Test case: 50, 59 -> 0.

Test case: -10 4

Can the input contain 5?

You say: "The start number will always be smaller than the end number." but one of your examples (-50,-59) directly contradicts this

What about giving a bounty on the most "mathematical" answer that you think?

JavaScript (ES6), 36 33 bytes
Takes input with currying syntax (a)(b).
a=>F=b=>b<a?0:!/5/.test(b)+F(b-1)

Formatted and commented
a =>                 // outer function: takes 'a' as argument, returns F
  F = b =>           // inner function F: takes 'b' as argument, returns the final result
    b < a ?          // if b is less than a
      0              //   return 0
    :                // else
      !/5/.test(b) + //   add 1 if the decimal representation of b does not contain any '5'
      F(b - 1)       //   and do a recursive call to F with b - 1

Test cases

let f =

a=>F=b=>b<a?0:!/5/.test(b)+F(b-1)

console.log(f(1)(9))
console.log(f(4)(17))
console.log(f(50)(60))
console.log(f(-50)(-59))

(I normally prefer test over exec when you only need a boolean.)

@Neil That makes more sense indeed. Updated.

NB: I couldn't find any tip about ES6 currying syntax, so I wrote one.

Wow, that's a great answer! Almost two times smaller than mine... Can you explain a bit how it works? I can see you call F recursively and save its return value which is based on the regex. But that currying syntax? How does that happen? Its so mind-blowing to me.

Assuming I read your snippet correctly, you can remove the b<a check because of this line in the question: The start number will always be smaller than the end number.

@TheLethalCoder b<a is there to stop the recursion after counting through all numbers from b to a, so removing it would just cause an infinite recursion.

@ETHproductions I wasn't 100% I was right as I'm not that familiar with JavaScript :)

@HristiyanDodov The unnamed outer function takes a as argument and returns the F function, which in turn takes b as argument and -- as you noticed -- is called recursively to iterate from b to a, incrementing a counter for all integers that do not contain a 5 in their decimal representation.

@Arnauld you should probably add that explanation to the body of your answer.

@PatrickRoberts Done :)

Strict mode might be angry with you. :)

@Arasuvel Thanks for accepting this. But since this is a code-golf challenge, you should either accept the shortest code or no answer at all.

Jelly, 8 7 bytes
-1 byte thanks to Dennis (use fact that indexing into a number treats that number as a decimal list)
rAw€5¬S

TryItOnline!
How?
rAw€5¬S - Main link: from, to    e.g. -51, -44
r       - range(from, to)        e.g. [-51,-50,-49,-48,-47,-46,-45,-44]
 A      - absolute value         e.g. [51,50,49,48,47,46,45,44]
  w€    - first index of... for €ach (0 if not present)
    5   - five                   e.g. [1,1,0,0,0,0,2,0]
     ¬  - logical not            e.g. [0,0,1,1,1,1,0,1]
      S - sum                    e.g. 5

* The absolute value atom, A is necessary since a negative number cast to a decimal list has negative entries, none of which would ever be a 5 (the given example would count all eight rather than two).

rAw€5¬S saves a byte.

@Dennis thanks! Is my description "treats that number as a decimal list" accurate?

Pretty much. w casts an integer argument to its decimal digits.

Bash + grep, 17 bytes
seq $@|grep -cv 5

Try it online!

2sable, 6 5 bytes
Saved a byte thanks to Adnan
Ÿ5¢_O

Try it online!
Explanation
 Ÿ      # inclusive range
  5¢    # count 5's in each element of the range
    _   # negate
     O  # sum

Note: This works due to a bug in ¢ making the function apply itself to each element instead of counting matching elements in the list.

You can remove the ``` as it behaves the same on arrays :p.

@Adnan: Thanks! I was gonna test that but forgot ;)

Python2, 59 55 52 51 47 43 42 bytes
f=lambda a,b:a<=b and-(`5`in`a`)-~f(a+1,b)

A recursive solution. Thanks to @xnor for giving me motivation to find a solution using logical operators! Also, thanks to @JonathanAllan and @xnor for guiding me and chopping the byte from 43 to 42!
Other attempts at 43 bytes
f=lambda a,b:a<=b and-~-(`5`in`a`)+f(a+1,b)
f=lambda a,b:a<=b and 1-(`5`in`a`)+f(a+1,b)

Would if!\x`.count('5')` work?

@Titus Python has not operator that is ! in C-like languages, but that takes 3 bytes :(

Think about using logical short-circuiting with and and or.

@xnor Got it, thanks! I had to only use and though.

Yup, nicely done! Now think about shortening that not.

@xnor I can't seem to get to the right solution... I can do ~- before the parentheses, but that negates the result, which I fix with another minus sign... bringing the solution back to 43 bytes :/ Any hints?

You're really close! Keep trying stuff.

@xnor I'm still not getting it under 43 bytes :/ I need to negate the ('5'in'a') expression, without Python making an implicit cast to boolean, but each operator that I use, makes the cast.

Let us continue this discussion in chat.

05AB1E, 8 7 6 bytes
Saved a byte thanks to Adnan
Ÿ5.å_O

Try it online!
Explanation
Ÿ         # inclusive range
 5.å      # map 5 in y for each y in the list
    _     # logical negation
     O    # sum

05AB1E also has vectorized å, which is .å, so you can do Ÿ5.å_O for 6 bytes.

negate meaning -n, or n==0?1:0?

@ETHproductions: Sorry, that was unclear. I meant logical negation, so n==0?1:0

Pyth, 9 8 bytes
Saved a byte thanks to FryAmTheEggman!
lf-\5T}E

Explanation:
        Q # Input
      }E  # Form an inclusive range starting from another input
          #   order is reversed, but doesn't matter
 f-\5T    # Filter by absence of '5'
l         # Count the number of elements left

Try it online!

Bash / Unix utilities, 21 bytes
seq $*|sed /5/d|wc -l

Try it online!

Haskell, 39 bytes
s!e=sum[1|x<-[s..e],notElem '5'$show x]

Try it online! Usage:
Prelude> 4 ! 17
12

Explanation:
             [s..e]                     -- yields the range from s to e inclusive
          x<-[s..e]                     -- for each x in this range
          x<-[s..e],notElem '5'$show x  -- if the char '5' is not in the string representation of x
       [1|x<-[s..e],notElem '5'$show x] -- then add a 1 to the resulting list
s!e=sum[1|x<-[s..e],notElem '5'$show x] -- take the sum of the list

Perl 6, 23 bytes
{+grep {!/5/},$^a..$^b}

Try it online!
How it works
{                     }  # A lambda.
              $^a..$^b   # Range between the two lambda arguments.
  grep {!/5/},           # Get those whose string representation doesn't match the regex /5/.
 +                       # Return the size of this list.

Groovy, 47 45  43 40 bytes
{a,b->(a..b).findAll{!(it=~/5/)}.size()}

This is an unnamed closure. findAll is similar to adding an if condition in a list comprehension in python.
Try it online!

Mathematica, 46 44 42 bytes
Thanks to alephalpha and DavidC for saving 2 bytes each!
Tr@Boole[FreeQ@5/@IntegerDigits@Range@##]&

Unnamed function taking two integer arguments and returning an integer. IntegerDigits@Range@## converts all the numbers between the inputs into lists of digits; FreeQ@5 tests those lists to decide which ones do not contain any 5. Then Boole converts booleans to zeros and ones, and Tr sums the results.
Other solutions (44 and 47 bytes):
Count[Range@##,x_/;IntegerDigits@x~FreeQ~5]&

IntegerDigits@x~FreeQ~5 determines whether the list of digits of a number is free of 5s, and Count[Range@##,x_/;...]& counts how many numbers between the inputs pass that test.
Tr[Sign[1##&@@IntegerDigits@#-5]^2&/@Range@##]&

1##&@@IntegerDigits@#-5 takes the list of digits of a number, subtracts 5 from all of them, and multplies the answers together; Sign[...]^2 then converts all nonzero numbers to 1.

Count[Range@##,x_/;IntegerDigits@x~FreeQ~5]&

Tr@Boole[FreeQ@5/@IntegerDigits@Range@##]&

R, 33 bytes
f=function(x,y)sum(!grepl(5,x:y))

Usage:
> f=function(x,y)sum(!grepl(5,x:y))
> f(40,60)
[1] 10
> f(1,9)
[1] 8
> f(4,17)
[1] 12

Octave, 36 bytes
@(m,n)sum(all(dec2base(m:n,10)'-52))

Try it online!

PHP 7.1, 57 55 bytes
for([,$a,$b]=$argv;$a<=$b;)$n+=!strstr($a++,53);echo$n;

Run with php -r '<code>' <a> <b>

Isn't this PHP7.1 syntax?

@aross: It is. But PHP 7.1 is older than 5 hours (pubished on December, 1)

of course, I just asked because I'm used to specifying the version if it's 7 or up. That's also kind of the convention for Python

Convention for PHP - as far as I have seen - is to use the most recent version unless specified otherwise.

I don't think many people have the latest minor version. The least common denominator at the moment would probably be 5.5. Personally I'm using FC 25 (considered pretty cutting edge), which currently distributes PHP 7.0. If you're on Windows you probably need to update manually.

@aross What is FC?

v5.5 shouldn't be considered lcd, it was end-of-lifed six months ago...

FC is Fedora Core. @AlexHowansky: right, I forgot about 5.6. But I doubt even 7.0 is the dominant version at the moment, never mind 7.1

Ruby, 36 35 bytes
->a,b{(a..b).count{|x|!x.to_s[?5]}}

Thx IMP1 for -1 byte

Doesn't this return the list without the numbers containing 5, rather than the size of that list?

You are right, I have copy/pasted the wrong version.

You can also use ?5 (the '5' character) instead of /5/ in the search to save a byte.

Java 7, 80 78 bytes
int c(int a,int b){int r=0;for(;a<=b;)r+=(""+a++).contains("5")?0:1;return r;}

Ungolfed:
int c(int a, int b){
  int r = 0;
  for (; a <= b; ) {
    r += ("" + a++).contains("5")
          ? 0
          : 1;
  }
  return r;
}

Test code:
Try it here.
class M{
  static int c(int a,int b){int r=0;for(;a<=b;)r+=(""+a++).contains("5")?0:1;return r;}

  public static void main(String[] a){
    System.out.println(c(1, 9));
    System.out.println(c(4, 17));
  }
}

Output:
8
12

PowerShell, 42 41 bytes
param($a,$b)$a..$b|%{$z+=!($_-match5)};$z

Called from the command line as .\no5s.ps1 1 20

You can drop the space to save a byte. With strictly numerical regex patterns, you don't need a delimiter (e.g., -replace3 or -split1 or -notmatch5).

Ah, nice, thanks @AdmBorkBork

Regex  (Perl / PCRE), 160 147 bytes
^(?(?=-x*,(?!-))-?+x*(,x*(?!$))?|-?(?=(x*),-?(x*))(?=(x*),?(?=\2)(?=\3)(x*,-?|[^,]*)(x*))\4,?+x*)(?!((?=(x+)(\8{9}x*))\9)*(x{10})*x{5}\b)(?(4)\4\6)
Try it online! - Perl
Try it online! - PCRE (faster)
Takes its input in unary, as two strings of x characters whose lengths represent the numbers, with optional - signs on their left side, joined by a , delimiter. Returns its output as the number of ways the regex can match. (The rabbit emoji indicates this output method.)
Most of the logic of this regex is taken up with handling the logic of integer ranges. It's rather unnatural... literally. Natural numbers (including zero) are much easier for a regex to operate on.
^
(?(?=-x*,(?!-))
    # Do the following if A is negative and B is nonnegative
    -?+                     # skip sign of A, if any
    x*                      # handle the range from larger to zero, inclusive
    (,x*(?!$))?             # handle the range from B inclusive to zero exclusive
|
    # Do the following if A is nonnegative or B is negative
    -?                      # skip sign of A, if any
    (?=
          (x*),             # \2 = abs(A);
        -?(x*)              # \3 = abs(B)
    )
    (?=
        (x*),?(?=\2)(?=\3)  # \4 = what to skip so tail = the larger of A or B;
                            # tail = the larger of A or B
        (x*,-?|[^,]*)(x*)   # \6 = {the smaller of A or B} - \4
    )
    \4,?+                   # tail = the larger of A or B
    x*                      # handle the range from larger to {smaller or zero}
)
(?!                         # Negative lookahead - assert this can't match
    (
        (?=(x+)(\8{9}x*))   # \8 = floor(tail / 10); \9 = tail - \8
        \9                  # tail = tail - \9 == \8
    )*                      # Iterate the above any number of times, minimum zero
    (x{10})*x{5}\b          # Assert tail % 10 == 5
)
(?(4)\4\6)                  # If \4 is set, clamp the range at the smaller end

It uses conditionals, which are not supported by ECMAScript, but it'd be easy enough to port (though the regex would be even longer). The  output method is required for this algorithm to be possible in ECMAScript (there isn't yet a regex engine that can emulate ECMAScript and count possible matches, but I'm planning on adding this to RegexMathEngine soon).
Regex (.NET), 163 bytes
^(?=(-x*,(?!-))?)(?>-?)(?(1)|(?=(x*),-?(x*))(?=(x*),?(?=\2)(?=\3)(x*,-?|[^,]*)(x*))\4(?>,?))(?(,)(?(1),)|(?(((?=(x+)(\8{9}x*))\9)*(x{10})*x{5}\b)|())x?)*(?(4)\4\6)
Try it online!
Returns its output as the capture count of group \11.
^
(?=
    (-x*,(?!-))?            # \1 = set iff A is negative and B is nonnegative
)
(?>-?)                      # skip sign of A, if any
(?(1)
|
    # Do the following if A is nonnegative or B is negative
    (?=
          (x*),             # \2 = abs(A);
        -?(x*)              # \3 = abs(B)
    )
    (?=
        (x*),?(?=\2)(?=\3)  # \4 = what to skip so tail = the larger of A or B;
                            # tail = the larger of A or B
        (x*,-?|[^,]*)(x*)   # \6 = {the smaller of A or B} - \4
    )
    \4                      # tail = the larger of A or B
    (?>,?)                  # skip sign of B, if any
)
                            # First handle the range from larger inclusive to
                            # {smaller inclusive or 0 exclusive}
(?(,)
    (?(1),)                 # If crossing from negative to nonnegative, handle
                            # the inclusive range from B to 0
|
    (?(
        (
            (?=(x+)(\8{9}x*))   # \8 = floor(tail / 10); \9 = tail - \8
            \9                  # tail = tail - \9 == \8
        )*                      # Iterate the above any number of times
        (x{10})*x{5}\b          # Assert tail % 10 == 5
      )
    |
        ()                  # Push a capture onto the \11 stack
    )
    x?                      # Advance by 1, but if already at the end, allow the
                            # loop to iterate once more so as to include 0 in
                            # the count.
)*
(?(4)\4\6)                  # If \4 is set, clamp the range at the smaller end

It could also be ported to an output method of the sum of the lengths of two capture groups (two, because the output can exceed the largest of the two inputs), though this would probably make it significantly longer.

Thunno 2 S, 6 bytes
Id5ȷc~

(No ATO link since it's down at the moment)
Explanation
Id5ȷc~  # Implicit input   ->    1,                                  10
I       # Inclusive range  ->   [1,  2,  3,  4,  5,  6,  7,  8,  9,  10]
 d      # Cast to digits   ->  [[1],[2],[3],[4],[5],[6],[7],[8],[9],[1,0]]
   ȷ    # To each list:    ->   [1] [2] [3] [4] [5] [6] [7] [8] [9] [1,0]
  5 c   #  Count 5s        ->    0   0   0   0   1   0   0   0   0   0
     ~  # Logical NOT      ->   [1,  1,  1,  1,  0,  1,  1   1,  1,  1]
        # Implicit sum     ->                      9
        # Implicit output

Python 2, 61 56 bytes
lambda a,b:len([n for n in range(a,b+1) if not"5"in`n`])

-5 bytes thanks to tukkaaX

Don't get discouraged! Having fun and challenging yourself is what matters. You can remove two whitespaces at not "5" in :) Also, if you're using Python2, you can surround x with `` quotes, instead of doing str(x).

@TuukkaX Thanks! also removed space between in and `x`

You can remove the []. You also don't need the space before if.

@Dennis I tried that already, but it complains that "object of type 'generator' has no len()".

@TuukkaX Right. lambda a,b:sum(not"5"in`n`for n in range(a,b+1)) works though. https://tio.run/nexus/python2#S1OwVYj5n5OYm5SSqJCok2RVXJqrkZdfomSqlJmXkJeQll@kkKeQmadQlJiXnqoBVKFtqKn5v6AoM69EIU3DRMfQXPM/AA

Batch, 95 bytes
@set/an=0,i=%1
:g
@if "%i%"=="%i:5=%" set/an+=1
@set/ai+=1
@if %i% leq %2 goto g
@echo %n%

Manually looping saves some bytes because I need the loop counter in a variable anyway.

Python 2, 54 bytes
i,j=input();k=0
while i<=j:k+=not"5"in`i`;i+=1
print k

Try it online!
Not the shortest Python answer Uses same algorithm but a different way of implementing with a while loop and is not a lambda function.

It is a program and not a function and it uses while instead of for. What is not different? OK, it is still looking for a string "5" inside the incremented input, agreed. Is there a better way?

That's exactly what it is and that's why it is deferent.  Sorry, maybe should have made my comment different.

Same algorithm, different way of implementing. No problem with your comments.  Is that better worded?

It is, yes :) I'll remove these comments to make the comment section look clean.

PHP, 56 bytes
for($i=$argv[1];$i<=$argv[2];)trim(5,$i++)&&$x++;echo$x;

Run like this:
php -r 'for($i=$argv[1];$i<=$argv[2];)trim(5,$i++)&&$x++;echo$x;' 1 9 2>/dev/null;echo
> 8

A version for PHP 7.1 would be 53 bytes (credits to Titus):
for([,$i,$e]=$argv;$i<=$e;)trim(5,$i++)&&$x++;echo$x;

Explanation
for(
  $i=$argv[1];          # Set iterator to first input.
  $i<=$argv[2];         # Loop until second input is reached.
)
  trim(5,$i++) && $x++; # Trim string "5" with the characters in the
                        # current number; results in empty string when
                        # `5` is present in the number. If that is not
                        # the case, increment `$x`

echo$x;                 # Output `$x`

Ah dang I forgot about the second trim parameter again.

C++ | in too many bytes, 165 125 thanks to Christoph!
int main(){int c=0;for(int i=0;i<=8;i++){int d;int n=i>=0?i:-i;while(n!=0){if(d=n%10==5){break;}n=n/10;c++;break;}}return c;}

I took the liberty of creating a function e_ to determine if a 5(or any other number) is present in an integer instead of using to_string() and .find() so that must count for something. note: e_ is only declared as an extra function in the un-golfed version for readability.
un-golfed:
int e_(int e,int i){
    int d;
    int n=i>=0?i:-i;
    while (n != 0){
        d=n%10;
        if (d==e){
        return 1;}
        n=n/10;}
        return 0;}
int main() {
    int l = 1;int h = 8;int e = 5;int c = 0;
    for(int i=l; i<=h; i++){
        if (e_(e,i)==0)
        c++;}
    return c;}

How e_ function works:
int n=i>=0?i:-i; Inverses our number if it is less than 0 so it's always positive. d=n%10; Divides it by 10 and gets remainder (n%base; will always return the last digit of an integer). We check that it equals 5, if it does the number can be discarded, if not n=n/10; removes the end digit and loops again.

#include <iostream> and using namespace std; can be dropped. Declaring an extra function is not going to save you bytes. if (e_(e,i)==0)  c++;could be reduced to c+=e_(e,i)==0;. Come on ! You can do better ! :)

Your right declaring an extra function is not going to save me bytes which is why It was only left in the un-golfed version for readability, <iostream> and namespace std; are unnecessary not sure why I didn't realise, habit I guess... thanks for the input and pointing out my mistake :)

CJam "easy pure mathematics solution", 60
{{Ab5+_,\_5#)<\9e]);_4f>.m9b}%}:F;q~_:z$\:*0>{((+F:-}{F:+)}?

Try it online
It takes the numbers in any order, in an array.
Explanation:
One core problem is to calculate f(n) = the number of non-5 numbers from 1 to n (inclusive) for any positive n. And the answer is: take n's decimal digits, replace all digits after the first 5 (if any) with 9, then replace all digits 5..9 with 4..8 (decrement), and convert from base 9. E.g. 1752 → 1759 → 1648 → 1*9^3+6*9^2+4*9+8=1259. Basically, each digit position has 9 acceptable values, and a 5xxxx is equivalent to a 49999 because there are no more valid numbers between them.
Once we solved this, we have a few cases: if the input numbers (say a and b, a<b) are (strictly) positive, then the result is f(b)-f(a-1). If they are negative, then we can take the absolute values, reorder them and use the same calculation. And if a<=0<=b then the result is f(-a)+f(b)+1.
The program first implements the function F as described above (but applied to each number in an array), then reads the input, converts the numbers to the absolute value and reorders them, and uses one of the 2 calculations above, based on whether a*b>0 initially.

Not "pure" but nice method. here, get a +1 :)

@MatthewRoh thanks, but what do you mean not pure? It's a solution that does fairly direct mathematical calculations on the input numbers, without iterating through the range. What else were you expecting?

Swift 52 bytes
($0...$1).filter { !String($0).contains("5") }.count

Since your challenge is a codegolf challenge, you should include your bytecount. Also, in codegolf (at least here), it's a requirement that all programs muse be actually contending (e.g. your function name can be just a single character, your actual function can probably be reduced to a single line). I don't know Swift, you might have to correct me on stuff.

SmileBASIC,  55 bytes
INPUT S,E
FOR I=S TO E
INC N,INSTR(STR$(I),"5")<0NEXT?N

Nothing special, just uses INSTR and STR$ to check for 5.

Hoon, 110 94 bytes
Hoon's range function, gulf, doesn't work for signed integers, which increases the length by a bit :(
=+
si^f=:(curr lien test 53)
|=
{a/@s b/@s}
|-
?:
=(a b)
(f <b>)
(add (f <a>) $(a (sum -1 a)))

Use the signed integer library. Create a function f: :(a b c d) is a macro that expands into (a b (a c d)) so this is (curr lien (curr test 53)), aka create a curried function that tests if any element of a list is 53 ('5')
Create a function that takes a and b. Create a loop: if a==b return f(tostring(b)), else return add(f(tostring(a)) recurse(a=a+1))
> =f =+
  si^f=:(curr lien test 53)
  |=
  {a/@s b/@s}
  |-
  ?:
  =(a b)
  (f <b>)
  (add (f <a>) $(a (sum -1 a)))
> (f -1 -9)
8
> (f -4 -17)
12
> (f -50 -60)
1
> (f --59 --50)
0

(Hoon's signed integers use - as a prefix, so --5 is negative 5 and -5 is positive 5)

C#, 77 bytes
(n,m)=>{var g=0;for(var i=n;i<m+1;i++)g+=(i+"").Contains("5")?0:1;return g;};

Anonymous lambda call.
Uses n (first number) and m (last number) as input, then checks via string containment ("".Contains("")).

I'm not the one downvoting, but modulo 5 isn't the correct solution for the challenge given by OP. It should exclude anything containing the digit 5 in its number, so 10 (which your answer wouldn't count) should be counted.

@KevinCruijssen Fixed.

This doesn't compile as g must be initialised when stated as it is named var so you need var g=""; and you can use currying i.e. n=>m=>

Also this outputs the list not the count

Fixed both of this. @TheLethalCoder

I meant it should output the count of items in the range not the items added together, see the test cases in the OP. This is still not working.

@KevinCruijssen With your edits this is essentially my answer...

@TheLethalCoder Ah, didn't realize there was a third C# answer.. I'll delete my comment and upvote your answer. :) @ devRicher: If you change ?0:i in your current code to ?0:1 it should work.

@KevinCruijssen Well I added 2 because the logic/code was essentially completely different

C 143 141 132 122 bytes
f(a,b){j=0,k,f;for(;a<=b;a++){k=a;f=0;while(k!=0){if(abs(k%10)==5){f=1;break;}else f=0;k/=10;}if(f<1)j++;}printf("%d",j);}

This is a solution that adopts a mathematical approach and checks every digit for number 5. Can definitely be shortened!
Ungolfed version:
  void f(int a,int b)
  {
       int j=0,k=0,f=0;

       for(;a<=b;a++)
       {
          k=a;f=0;

          while(k!=0)
          {

            if(abs(k%10)==5) // If one of the digits in the number is 5, set a flag and break while loop, else reset the flag and continue checking.
            {
              f=1;
              break;
            }
            else
              f=0;

            k/=10;

          }

       if(f<1)
         j++;
      }
      printf("%d ",j);

  }

@TuukkaX Thanks for saving 2 bytes.
@nmjcman101 Thanks for saving 9 bytes.
@nmjcman101 Thanks for saving 10 bytes more, make so much sense. :)

Redundant whitespace at &&. I think that you can do a^b in each case you check for disequality, such as abs(i%10)!=5.

@TuukkaX I'm gonna have to modify this answer anyways since it would not work for 150, 500

Useless whitespace at (f==0) j++. If f can't be negative, you can check whether f<1.

@TuukkaX You're right! Updated!

You don't need the first if(a<b).  OP says "The start number will always be smaller than the end number."

@nmjcman101 Thanks for the clarification regarding input validation.

More suggestions: i is useless, do for(;a<=b;a++) , l is useless also, do abs(k%10)==5.  use a for loop instead of a while for(;k;k/=10).  Then about the logic, there's two paths:  current path - don't have the else in the while, then you don't need to break b/c f will stay 1 until the end.  Also, set f=1 initially and then if(.==5)f=0; so that at the end you can do if(f)j++ or j+=f;  The other option is to do if(==5)j--,break; in the loop and then always do j++ and skip the f entirely, I don't know which is shorter

Sure, It is mathematical, but not mathematical as mine. :P

while(k){f|=abs(k%10)==5;k/=10;}j+=1-f;} should save a bit.  (Oh, I see, this is like what @nmjcman101 is saying.)

TI-BASIC, 37 34 bytes
:Prompt A,B
:Delvar CFor(N,A,B
:C+not(inString(toString(N),"5→C
:End
:C

I believe count is correct, however toString() is only supported on the TI-84+ CE calculators which I do not have, so I was unable to count it or test it to make sure it runs correctly. I therefore counted it as 2 bytes in addition to the others which were counted directly on a TI-84.
Thx to Jakob Cornell for removing

Try DelVar C on line 2. Then you can combine lines 2 and 3.
Also on line 4, not( should work in place of 0=.
And finally, print and "return" C on the last line by omitting Disp.

Wow, thx, I'll make the changes. Looking at this again now, yeah I definitely wasn't thinking about cutting that down, especially with Disp C  :(

JavaScript (ES6), 58 56 49 bytes

let f =

(s,e)=>{for(c=0;s<=e;)c+=!/5/.test(s++);return c}

console.log(f(1, 9));
console.log(f(4, 17));
console.log(f(-9, -1));

Golfed 7 bytes thanks to ETHproductions.

You can use c+=!/5/.test(s++) to save a few bytes :-)

Thanks a lot! I had to delete my golfs, though. I was so proud of them. :(

I think you can use currying i.e. s=>e=>

The top answer uses currying syntax. I won't edit mine because it would become almost the same. Thanks for pointing that out, though!

Java 7, 77 bytes
This is an improvement of Kevins Answer, but since I don't have the reputation to comment yet, this new answer will have to do.
So what I did was:

Replace the indexOf statements with contains (-1 byte)
Move the incrementing part of the for-loop into the conditional statement (-2 bytes)

for-loop (77 bytes):
int c(int a,int b){int r=1;for(;a++<b;)r+=(""+a).contains("5")?0:1;return r;}

recursive (79 bytes):
int d(int r,int a,int b){r+=(""+a).contains("5")?0:1;return a!=b?d(r,a+1,b):r;}

Output:
8
12

8
12

Test it here !

Wellcome to PPCG ! Nice findings in an already quite nicely golfed answer. I don't know about Java that much but shouldn't (""+a).contains("5")?0:1 be replacable by !(""+a).contains("5")?

@Christoph sadly no, since in Java a boolean really is just a boolean. So a ternary operation is the only way to go.

Hm that's sad. What about (""+a).contains("5")||r++?

@Christoph that won't work either, because you can't have a boolean expression on its own. I've been trying to make it work in other places (like the for-loop declaration) but not with much success. Nice idea tho ;)

C#, 67 bytes
a=>b=>{int c=0;for(;a<=b;)c+=(a+++"").Contains("5")?0:1;return c;};

I was hoping to use for(int c=0;...) but then it fails to compile because the return is outside the scope for c

MATL, 10 bytes
&:!V53-!As

Try it online!
Explanation
        % Implicitly grab two input arguments
&:      % Create an array from [input1....input2]
!V      % Convert to a string where each number is it's own row
53-     % Subtract ASCII '5' from each character.
!A      % Detect which rows have no false values (no 5's). Returns a logical array
s       % Sum the logical array to get the # numbers without 5's
        % Implicitly display the result

PowerShell, 37 36 bytes
($args[0]..$args[1]-notmatch5).Count

Try it online!

You can drop the space to save a byte. With strictly numerical regex patterns, you don't need a delimiter (e.g., -replace3 or -split1 or -notmatch5).

Doh, how'd I miss that?! Thanks @AdmBorkBork

Actually, 13 bytes
u@x`$'5íuY`░l

Try it online!
Explanation:
u@x`$'5íuY`░l
u@x            range(a, b+1)
   `$'5íuY`░   take where:
    $            string representation
     '5íuY       does not contain "5"
            l  length

CJam, 18 17 bytes
q~:S-){S+s'5&!},,

Input is end number followed by start number.
Try it online!
How it works
q~                  Read and evaluate all input. Pushes end and start.
  :S                Save the start in S.
    -)              Subtract and increment, computing L =: end - start + 1.
      {       },    Filter [0 ... L-1]; for each N in the range:
       S+             Add S to N.
         s            Cast to string.
          '5&         Intersect with '5'.
             !        Take the logical NOT.
                ,   Compute the length of the resulting array.

Perl 5, 29 bytes
perl -le 'print 0+grep!/5/,shift..shift' 4 17               #prints 12

Nice answer, welcome to the site!

C++, 84 81 + 16 = 100 97 bytes
int f(int a,int b){int c;while(a<=b)c+=!~std::to_string(a++).find('5');return c;}

#include<string> - +16
Ungolfed:
int func(int start, int end) {
  // Defaults to 0
  int count;

  // Iterates from start to end (inclusive) and increments the count by one
  // if '5' is not found
  while (start <= end)
    count += !~std::to_string(start++).find('5');

  return count;
}

The function itself should be pretty clear. I essentially just iterate from start (or a) to end (or b). The only more complex line is this:
count += !~std::to_string(start++).find('5');

However it is also easiy explained. find returns std::npos which is the maximum value size_t can hold (exact value depends on how the compiler defines it) when the character cannot be found. Which essentially means the it is an integer value filled with binary ones. ~ performs a binary not, meaning that the value is 0 when no 5 character could be found and not 0 when it could. Then ! converts it to a bool (0 => false, everything else => true) and itverts it. So now when the 5 could be found the value is false and true if it could not. Then it gets added to the count variable. (true => 1, false => 0).
Try it online!
@Christoph Thanks for giving me the idea to save 3 bytes

std::to_string(start++).find('5')<0;

@Christoph since size_t (the return type of find) is an unsiged integer the check < 0 is always false since -1 becomes int max. However using bitwise manipulation I managed to work out a short solution. Thanks for giving me the idea for it though!

Damn you're right! nice that I could help anyway :)

Vyxal s, 5 bytes
ṡ5vc†

Try it Online!
Port of the 05ab1e/2sable answer
Explained
ṡ5vc†
ṡ     # inclusive range
 5vc  # is the number 5 in each number?
    † # negate each item. s flag sums the list

Arturo, 36 bytes
$=>[enumerate&..&'x->¬in?{5}~{|x|}]

Try it!
$=>[                   ; a function where inputs are assigned to &
    enumerate&..&'x->  ; count in input range; assign current elt to x
        in?{5}~{|x|}   ; is the string "5" in x converted to a string?
        ¬              ; logical not
]                      ; end function

Lua, 65 bytes
n=0s,e=...for i=s,e do n=n+((i..''):find'5'and 0or 1)end print(n)

Try it online!

C#, 82 81 bytes
using System.Linq;a=>b=>Enumerable.Range(a,++b-a).Count(n=>(n+"").All(d=>d!=53));

Added as a separate answer as it's logic is different.

I think one of those two using System.Linq; should be removed (byte-count is correct, though). ;)

@KevinCruijssen Woops looks like I can't copy and paste!

SimpleTemplate, 63 bytes
This was harder than expected.
Expects each number as a single parameter in the class, outputting the number of element without 5.
{@eachargv as_}{@if"~5~"is not matches_}{@incX}{@/}{@/}{@echoX}

Ungolfed
{@each argv as argument}
    {@if "~5~"is not matches argument}
        {@inc result}
    {@/}
{@/}
{@echo result}

If I read this right you are returning the list of numbers in the range, you need to return the count.

@TheLethalCoder Crap. Ignore this...

Fixed! (I hope...)

Perl, 35 20+1 bytes
$\+=!/5/ for$_..<>}{

After considerable help from @Dada in the comment below, this turned into a beautiful 20 bytes - plus 1 for the p. I've left my original answer below, for posterity.
for(shift..shift){$z+=!/5/}print$z;

Call from command line as no5s.pl 1 20.
First Perl golf, so hopefully someone can improve it :)
Also using Strawberry Perl on Windows, so I can run no5s.pl 1 20 directly on the command line and it works - might try using perl -e ...

Nice first Perl golf. shift..pop will save you one 2 bytes. Using the for in statement modifier position ($z+=!/5/ for shift..pop) should save3 more bytes. Using $\  instead of $z should save two bytes (since just print with no argument will print it). Drop the last semi column. And finally, you can combine all of this and take the numbers from stdin instead of @ARGV. It becomes then perl -pe '$\+=!/5/ for$_..<>}{' (with a little trick with -p and }{, see here).

Clojure, 73 bytes
(fn[i a](count(for[n(range i(inc a)):when(every? #(not=\5 %)(str n))]n)))

I had to rollback my previous "improvement", as somehow count was dropped from the new version, and it ended up being longer when I fixed it.
Filters the range of numbers; selecting only the numbers where every digit is not a 5.
(defn count-minus-5 [mi ma]
  (count ; Get the length of the resulting list
    ; Comprehension over the range mi(n) to ma(x).
    (for [n (range mi (inc ma))
          ; Only allow the number when every digit isn't a 5.
          :when (every? #(not= \5 %) (str n))]
      n)))

I think your answer is missing a count, the function "...should return the number of integers within it...".

@NikoNyrh That'd weird. Somehow it got taken out of the golfed version (note the preformed version has it). I'll update it in a bit.

*preformed -> pregolfed

QBIC, 33 32 bytes
Saved a byte by reversing the conditional and moving the increment to ELSE
::[a,b|~instr(!c$,@5`)|\d=d+1}?d

Explanation:
::       get a and b from the command line
[a,b|    FOR c = a; c <= b; c++
~instr(  IF indexOf ( instr is a QBasic function that doesn't have a QBIC equivalent)
    !c$  our loop iterator cast to string
    ,@5` a literal 5
)        instr returns 0 if it didn't find '5', which is truthy.
|        THEN --> Don't do anything for values with a '5'
\d=d+1   ELSE count this number into the total
}        Close all constructs (END IF, NEXT c)
?d       Print 'd': the total number of numbers without a '5'

Perl 6, 21 bytes
+(+*..+*).grep:{!/5/}

Basically equivalent to smls's solution, but I was able to shave off a couple of bytes by expressing the range as (+*..+*) and eliminating the brackets.  (The plusses are necessary, otherwise the stars would be interpreted as negative or positive infinity rather than as arguments to the WhateverCode lambda.)

Scala, 51 bytes
(a:Int,b:Int)=>a to b map{_+""indexOf "5"}count(0>)

I haven't been able to concisely combine the map and count.

Java 8, 68 bytes
(a,b)->IntStream.range(a,b+1).map(i->(""+i).contains("5")?0:1).sum()

This is basically just a rewrite of the Java7 solution by @Kevin Cruijssen to Java8.
And I hope we don't care about imports here, otherwise it would be longer by 17 bytes due to the package).
Ungolfed:
(a,b)->IntStream.range(a,b+1)
  .map(i->(""+i).contains("5")?0:1)
  .sum()

Test code:
Try it here.
import java.util.function.BiFunction;
import java.util.stream.IntStream;

class M {
  public static void main (String[] args) {
    BiFunction<Integer, Integer, Integer> dontGimme5 =
      (a,b)->IntStream.range(a,b+1).map(i->(""+i).contains("5")?0:1).sum();
    System.out.println(dontGimme5.apply(1,9));
    System.out.println(dontGimme5.apply(4,17));
    System.out.println(dontGimme5.apply(-50,-59));
  }
}

Output:
8
12
0

C++, 187 bytes
int f(int a,int b){int r=0;for(int i=a;i<=b;i++){r++;for(int j=0;j<floor(log(abs(i)));j++){int k=floor(abs(i)%int(pow(10,j+1))/pow(10,j));if(k==5){r--;break;}}}return r;}

#include <cmath> - 16 bytes
I couldn't think of a purely mathematical way, so I did this.

Loop through a to b
Calculate the length with floor(log(abs(i)))
Get numbers of each digit with floor(abs(i)%int(pow(10, j + 1)) / pow(10,j))
If it is 5, subtract then move to next number

Still, isn't practical for code-golf, but used much math as I could.
Try it online!

You can remove all the unnecessary space to save bytes

@KritixiLithos Forgot it. thanks! by the way, do you like how it works?

By moving the int declarations around, you can save some bytes: https://tio.run/nexus/cpp-gcc#PU9BbsMgELz7FUhRJRBEtaP2UC3kL9jGyWIbIsDqweLtLiRtL7O7M6PR7AndsGyjIRJ9TMHo9Xqc/rlh1el@bdAlMtGKWlTs2V5HUK1ApYUVM0w@UECpekDO2R44f1JWtWDltPiyL/5GdR8pMsbAVtesXsqLfSuZ9OG/adcKyzvG3v@O4seJzkp9luTzGfrSc4acczBpC44EyMcW0d2I06uJDz0YEtMIz@KrRkcZ2RtCBr8lImX5pRNfrG7GjQsU5Tfo4wJNPn4A

somewhat around i/pow(10,j)%10 should save a lot of bytes. j<9 should work, too. There's still a lot to golf, keep trying !

TI-Basic, 43 bytes
Since linear regression to string is so costly, let's try a different approach.
DelVar AInput
For(I,X,Y
1
For(J,1,9
Ans and 5≠int(10fPart(I/10^(J
End
A+Ans→A
End

Old method, 55 bytes
Majority of the program size is converting number to string through linear regression... why wasn't there a built-in for this?
DelVar AInput
For(I,X,Y
{0,1→L₁
{0,A→L₂
LinReg(ax+b) Y₁
Equ►String(Y₁,Str1
A+not(inString(Str1,"5→A
End

P.S. (For both methods:) Since the last statement evaluated by the program is that seventh line, it will return the value as normal through Ans. Also, Input stores to X and Y similar to Prompt X,Y.

Clojure, 64 bytes
#(count(for[i(range % (inc %2)):when(not(some #{\5}(str i)))]i))

C++ (function), 115
int f(int a,int b){int r=b-a+1,t;while((t=a++)<=b)while(t!=0)if(abs(t)%10==5){r--;break;}else t/=10;std::cout<<r;}

C++ (full), 143
#include<iostream>
int main(){int a=0,b=4,r=b-a+1,t;while((t=a++)<=b)while(t!=0)if(abs(t)%10==5){r--;break;}else t/=10;std::cout<<r;return 0;}

Ungolfed version:
#include<iostream>
int main()
{
    int a=0, b=4, r = b-a+1, t;
    while((t = a++) <= b)
        while(t != 0)
            if(abs(t) % 10 == 5)
            {
                r--;
                break;
            }
            else
                t /= 10;
    std::cout<<r;
    return 0;
}


text:
ASCII Art "Flight Simulator"
EDIT
It appears that there has been some confusion following my typo in the original post which used a lowercase o to define the plane and then an uppercase later. Unfortunately this bug did not get picked up in the Sandbox. Since many members have written answers with both and since the typo was my fault I will allow either uppercase or lowercase o in the definition of the plane. I have added a new rule for this.
Background
I like ascii art animations as I tend to call them so here is another one. I don't think this is too difficult to implement so will hopefully get some short and interesting answers.
To all fellow community members
If you improve on your answer please modify your byte count as
old byte count new byte count
so we can see your progress. Thanks!
Challenge
Here is an ascii plane
--O--

Here is an ascii runway
____|     |____

The plane starts at 5 newlines above the runway. To prevent any clashes between metric and imperial systems and make this a truly international challenge I won't mention meters or feet. Example:
        --O--

____|     |____

The Plane must land exactly in the middle of the runway as shown below:
____|--O--|____

Input
The initial horizontal position of the plane is defined by an integer input which is used to reference the tip of the left wing i.e. it is between 0 and 10 inclusive.
Output
Each stage of the planes flight must be shown. Example below (input=10):
          --O--

____|     |____

         --O--

____|     |____

        --O--

____|     |____

       --O--

____|     |____

      --O--
____|     |____

____|--O--|____

To keep things simple, we are ignoring the laws of perspective. The runway stays the same size as you get closer.
Rules

Update The middle of the plane can be either an uppercase or lowercase o but whichever is chosen must be consistent throughout the code. If your language does not support the characters above feel free to use alternative ascii only characters.
The plane descends 1 line per frame.
The plane can only move 1 space to the left or right each time it descends one line. It does not have to move on each line of descent. As long as it finishes on the runway it is up to you when it moves right or left. You're the pilot!
No error handling required. You may assume that the input will always be a valid integer from 0-10 inclusive.
Output must consist of only the characters shown above (if your language does not support them the see edited first rule) and must be the same size i.e. must start 6 lines high by 15 characters wide. The height can decrease as it progresses as in the example above.
Program or function is fine but must produce an output as shown
above.
Leading/trailing spaces/newlines are fine by me.
Please feel free to clear the screen between output frames if you wish. This is not a requirement.
Standard loopholes prohibited as usual (although I don't think there are many that would help with this kind of challenge).
This is code golf so shortest answer is obviously the winner and will probably get most votes but may not necessarily be accepted as the best answer if some really interesting solution comes along in some unexpected language, even if it is longer. Feel free to post anything that meets the rules as long as it works.

Ungolfed reference implementation in Python 2 available at Try it online! so you can see how it looks for different input values.

I don't think it is kolmogorov-complexity as the output depends on the input

Thanks for the clarification @ovs. I'll remove that tag then.

Usually, the acceptance goes to the answer that complies best with the Objective Winning Criterion. You may get some flak if you accept another, longer answer.

Thanks @LevelRiverSt. Is there a meta post to clarify this? If not then maybe better to not accept any answer.

btw, I have accepted a longer answer before and given credit to the shorter answer as well with no probs from the community Previous challenge. Please see my Result comment at the end of the question. Was this wrong?

I'm not going to say if it's right or wrong, as that's something the community should judge. In answer to your previous comment, here's a meta question by someone with similar views to you. There are probably other meta questions out there. Note the voting on his answer and Helka Homba's http://meta.codegolf.stackexchange.com/q/8706/15599

Thanks for the link. Much as I respect your comments I'l go this my own way. If I get downvoted for what other community members think is the wrong decision on the accepted answer I will accept that. As I have said on a previous Meta  post (2nd answer from the top), I don't think we should take this too seriously.

I'll just leave this here… (See full listing.)

The plane is shown once in lowercase, and the rest of the time in uppercase. Are both variants allowed? (It does make a difference, see my Perl 6 solution...)

@smls Good catch and thanks for pointing it out. The plane should be uppercase - I have corrected the question. Apologies for any confusion caused.

Thought it seems in the TI-BASIC responses (they used O, not o), _ and | were replaced with - and either / or I, so why would the O matter

TI-BASIC, 61 bytes
Input A
A
For(B,1,5
ClrHome
Output(5,1,"----/     /----
Output(B,Ans,"--O--
Ans+6-median({5,7,Ans
End

Do you know of an online interpreter or download (For Linux) for testing? +1 for the answer assuming it works :)

Check out TilEm. It's the only one I could get working.

+1 for asking someone who may have had a different answer. Will certainly check out TilEm and thanks for the tip.

TI-BASIC, 62 bytes
:Input A
:A
:For(N,3,8
:ClrHome
:Output(8,1,"----I     I----
:Output(N,Ans,"--O--
:Ans+(Ans<6)-(Ans>6
:End

Note that TI-BASIC does not support _ or | and therefore I replaced with a capital I and -. This should not effect byte count.

OK, I'm on Linux. Can you recommend a download that I get to test this? btw, I assume it works until I find an interpreter so +1 :)

Unfortunately, no. I do have both Wabbitemu and TilEm installed on my Windows 10 computer, but I test the code on a physical TI-84+. Sorry

No problem! Just asking :)

Due to a lot of editing of code, the fastest alternated between this post and Julian Lachniet's, until we both came to the 60 byte conclusion, at which point I added clrhome and made byte count 62

TI-Basic?!  Nice!

Python 2, 107 bytes
n=input();h=5
while h:print' '*n+'--O--'+'\n'*h+'____|     |____\n';n-=cmp(n,5);h-=1
print'____|--O--|____'

Try it online
Simply hardcodes the last line for the landing plane. It can likely be golfed by re-using parts from before or being integrated into the loop.

Perl, 94 bytes
93 bytes of code + -p flag.
$\="____|     |____
";$p="--O--";for$i(-5..-1){print$"x$_.$p.$/x-$i;$_+=5<=>$_}$\=~s/ +/$p/}{

Try it online!

@ETHproductions Hope you enjoy the }{ (and the $" messing with the syntax highlighting).

JavaScript (ES6), 108 bytes
f=(a,b=5)=>b?" ".repeat(a)+`--O--${`
`.repeat(b)}____|     |____

`+f(a<5?a+1:a-1,b-1):"____|--O--|____"

Test it

f=
(a,b=5)=>b?" ".repeat(a)+`--O--${`
`.repeat(b)}____|     |____

`+f(a<5?a+1:a-1,b-1):"____|--O--|____"
<input type=number min=0 max=10 oninput=o.textContent=f(+this.value)><pre id=o>

Usage
Just call f with the index of the plane.
f(2)

Output
  --O--

____|     |____

   --O--

____|     |____

    --O--

____|     |____

     --O--

____|     |____

    --O--
____|     |____

____|--O--|____

You can add a snack stack snippet

Every time I ask a question the first answer is Javascript! +1

Hey, would be nice if people posted either a Tryitonline (don't know if that is possible with Javascript) or a different solution to the 10 example shown above. Can you post the output from e.g. 2 instead? :)

@ElPedro, you can execute JavaScript in your browser console, but there also are some online consoles. I'll add a link. I'll also change the example.

Thanks. No probs. I'm into old time Javascript where you need a web page to execute it. Guess I need to get with the times :) More serverside these days. Respect for the fast and cool answer.

Thanks a lot! I don't really get what you're saying about JavaScript being "more serverside". JavaScript is still a client-side programming language, but all big browsers let you execute your own JS through the console. As such, you still need a webpage. I think you're referring to JSFiddle, which just saves some JavaScript snippet and executes it when a URL is accessed.

No, my mistake on the wording. What I meant was I work more serverside (mostly Python and (unfotuntately) Java). 15 years ago I knew Javascirpt backwards. I guess it has progressed a long way since the old days :)

I think this is actually 104 bytes, unless I'm missing something...

Scala, 224 181 bytes
EDIT: I had no idea you could do "string"*n to repeat it n times! Scala continues to blow my mind. Missing the if(t>0) instead of if(t==0) was a rookie mistake. Thanks for the tips, Suma!

def?(x:Int,t:Int=5):Unit={var(p,o)=("--o--","")
o=s"____|${if(t>0)" "*5 else p}|____\n"
for(i<-0 to t)o=if(i!=0&&i==t)" "*x+p+o else "\n"+o
println(o)
if(t>0)?(x-(x-4).signum,t-1)}

Original remarks:
I figured a recursive solution would be fun to try. I'm relatively new to Scala, so I'm certain this is far from optimal.

You might want to read Tips for golfing in scala

You don't need the :Unit=. Omitting the equals sign will set the return type to Unit.

Also, why didn't you initialize o in the first line?. And since i is always >= 0, you can change i!=0&&i==t to i>0&i==t (3rd line).

Batch, 230 bytes
@echo off
set/ax=10-%1
set s=          --O--
for /l %%i in (0,1,4)do call:l %%i
echo ____^|--O--^|____
exit/b
:l
call echo %%s:~%x%%%
for /l %%j in (%1,1,3)do echo(
echo ____^|     ^|____
echo(
set/a"x-=x-5>>3,x+=5-x>>3

x is the number of spaces to remove from the beginning of the string s, so I subtract the parameter from 10. The last line is the nearest Batch has to x-=sgn(x-5).

Perl 6, 97 90 81 bytes
{say "{"{" "x 15}\n"x 5}____|     |____"~|("\0"x$^h+$_*(17-$h/5)~"--O--") for ^6}

Contrary to what it looks like, it outputs the *lower-case version of the plane (--o--), as allowed by the updated task description.
Try it online!
How it works
Bitwise string operators FTW!
{                                                  # Lambda accepting horizontal index $h.
    say                                            # Print the following:
        "{ "{ " " x 15 }\n" x 5 }____|     |____"  # The 15x6 background string,
        ~|                                         # bitwise-OR'd against:
        (
            "\0"                                   # The NULL-byte,
            x $^h + $_*(17 - $h/5)                 # repeated by the plane's offset,
            ~ "--O--"                              # followed by an OR mask for the plane.
        )
    for ^6                                         # Do this for all $_ from 0 to 5.
}

It works because bitwise string operators use the codepoint values of the characters at a given position in two strings, to calculate a new character at that position in the output string.
In this case:
space  OR  O   =  o
space  OR  -   =  -
any    OR  \0  =  any

For an uppercase-O plane, we could have used ~^ (string bitwise XOR), with a plane mask of \r\ro\r\r (+4 bytes for backslashes):
space  XOR   o  =  O
space  XOR  \r  =  -
any    XOR  \0  =  any

The formula for the plane's offset, h + v*(17 - h/5), was simplified from:
  v*16         # rows to the vertical current position
+ h            # columns to the horizontal starting position
+ (5 - h)*v/5  # linearly interpolated delta between horizontal start and goal

sed, 181 bytes + 2 for -nr flags
s/10/X/
:A
s/^/ /;y/0123456789X/-0123456789/;/[0-9]/bA;s/ -/P\n\n\n\n\n____|P|____/
:B
h;s/P([\n|])/--O--\1/;s/P/     /;s/^ *_/_/;p;/^_/q;x;s/\n//
/^ {5}$/bB;/ {6}/s/  //;s/^/ /;bB

Ungolfed
# Add leading spaces
s/10/X/
:A
    s/^/ /
    y/0123456789X/-0123456789/
/[0-9]/bA

s/ -/P\n\n\n\n\n____|P|____/

:B
    # Place plane in appropriate spot
    h
    s/P([\n|])/--O--\1/
    s/P/     /
    s/^ *_/_/
    p
    /^_/q
    x

    # Movement
    s/\n//
    /^ {5}$/bB
    # move left one extra, since we'll move right next line
    / {6}/s/  //
    s/^/ /
bB

Usage: $ echo 2 | sed -nrf flightsim.sed

Retina, 86 83 bytes
.+
$* --O--¶¶¶¶¶¶____|     |____
{*`$
¶
2D`¶
 ( {5})
$1
}`^ {0,4}-
 $&
 +
--O--
G`_

Try it online!
There is probably some sort of compression I could have used on the runway and the empty space over it, but anything I tried came up more expensive than plaintext (in Retina ¶ is a newline, so you can see the initial state in plaintext on the second line).

Scala, 177, 163, 159 137 bytes
def p(x:Int,t:Int=5,a:String="\n"):String=a+(if(t>0)
" "*x+"--O--"+"\n"*t+"____|     |____\n"+p(x-(x-4).signum,t-1)else"____|--O--|____")

Based on another answer, with significant reductions.

Python 2, 160 bytes
i,s,p,l,r,c,x=input(),' ','--O--','____|','|____',0,4
while x>=0:print'\n'.join([s*i+p]+[s*15]*x+[l+s*5+r])+'\n';c+=1;x-=1;i=((i,i-1)[i>5],i+1)[i<5]
print l+p+r

Try it online!
Here is the reference implementation golfed down to 160 from 384. Still a way to go I think. Just posted for fun and to encourage a better Python answer.

You can compete in your own challenge (see this meta post).

Can you just do while-~x?

Also I think you can write the bit where you either add or subtract from i as i+=(i<5)-(i>5)

Befunge-93, 136 130 bytes
&5>00p10p55+v
:::00g>:1-\v>:"____|     |_"
>:1-\v^\+55_$"--O--"10g
^\*84_$>:#,_10g::5v>:#,_@
<_v#!:-1g00+`\5\-`<^"____|--O--|____"

Try it online!
Explanation
&                          Read the plane position.
 5                         Initialise the plane height.
  >                        Begin the main loop.

   00p                     Save the current height.
      10p                  Save the current position.
         55+:              Push two linefeed characters.

         "____|     |_"    Push most of the characters for the airport string.
:::                        Duplicate the last character three times to finish it off.

   00g>:1-\v               Retrieve the current height, and then push
      ^\+55_$                that many copies of the linefeed character.

             "--O--"       Push the characters for the plane.

>:1-\v              10g    Retrieve the current position, and then push
^\*84_$                      that many copies of the space character.

       >:#,_               Output everything on the stack in reverse.

            10g::          Retrieve the current position and make two copies to work with.
                 5v        If it's greater than 5
                -`<          then subtract 1.
           +`\5\           If it's less than 5 then add 1.

        g00                Retrieve the current height.
      -1                   Subtract 1.
 _v#!:                     If it's not zero, repeat the main loop.

^"____|--O--|____"         Otherwise push the characters for the landed plane.
>:#,_@                     Output the string and exit.

Ruby, 94 bytes
->a{5.times{|i|puts" "*a+"--O--#{?\n*(5-i)}____|     |____

";a+=5<=>a};puts"____|--O--|____"}

Prints the plane's position followed by newlines and then the airport.
Then it moves the plane by 1, -1, or 0, depending on its position relative to 5.
After looping the above 5 times, it prints the plane in the airport.

QBIC, 93 91 84 bytes
:{X=space$(a)+@--O--`┘a=a-sgn(a-5)~t>-1|?X[t|?]t=t-1?@____|`+@     `+_fB|\_xB+A+_fB

Dropped some bytes by replacing the declaration of X$; optimised the FOR loop that prints the distance above-ground. Explanation below is for the old version, but it basically works the same.
For testing (and aesthetics) I had a slightly different version, at 103 bytes:
:{_z.5|_CX=Y[a|X=X+@ `]X=X+@--O--`
a=a-sgn(a-5)
~u>0|?X';`[u|?]u=u-1?@____|`+@     `+_fC|\_xC+_tB+_fC

These are functionally identical. The second one has the addition that the screen gets cleared between frames and that it halts for 0.5 seconds between frames.
Sample output
Note that I've added two newlines between frames. The most golfed code above does not add empty lines between frames, the cooler one clears the screen.
Command line: 10

          --O--

____|     |____

         --O--

____|     |____

        --O--

____|     |____

       --O--

____|     |____

      --O--
____|     |____

____|--O--|____

Explanation
Since I feel this touches upon many things I really like about QBIC, and gives a good insight in how some of its functions work under the hood, I've gone a bit overboard on the explanation. Note that QBIC is, at its core, an QBasic interpreter for Codegolf. QBIC code goes in - QBasic code comes out (and is subsequently executed).
:{      get the starting offset (called 'a') from the command line, and start a DO-loop

----  cool code only  ----
_z.5|_C At the start of a DO-loop, pause for half a second and clear the screen
---- resume golf-mode ----

---- #1 - The tip of the left wing is anywhere between 0 and 10 positions to the right.
----       Create the plane with the spacing in X$
X=Y          Clear X$
[a|          For each point in the current offset
X=X+@ `]     Add a space to X$
    - Every capital letter in QBIC references that letter+$, a variable of type String
    - @ and ` start and end a string literal, in this case a literal space.
    - ] ends one language construct (an IF, DO or FOR). Here, it's NEXT
X=X+@--O--`  Create the actual plane
    - @ and `once again create a string literal. Every literal that is created in this
      way is assigned its own capital letter. This is our second literal, so the body of
      our plane is stored in B$ (A$ contains the space, remember?)

---- #2 Adjust the offset for the next iteration
a=a-sgn(a-5) The clever bit: We have an offset X in the range 0 - 10, and 5 attempts to
             get this to be == 5. X - 5 is either positive (X = 6 - 10), negative
             (X = 0 - 4) or 0 (X=5). sgn() returns the sign of that subtraction
             as a 1, -1 or 0 resp. We then sub the sign from 'a', moving it closer to 5.

---- #3 Draw the plane, the empty airspace and the landing strip
~u>0|     Are we there yet?
    - ~ is the IF statement in QBIC
    - It processes everything until the | as one true/false expression
    - All the lower-case letters are (or better, could be) references to numeric
      variables. Since QBasic does not need to post-fix those, they double as 'natural'
      language: ignored by QBIC and  passed as literal code to the QBasic beneath.
    - The lower-case letters q-z are kinda special: at the start of QBIC, these
      are set to 1 - 10. We haven't modified 'u' yet, so in the first DO-loop, u=5

?X';`     If we're still air-borne, print X$ (our plane, incl. spacers)
    - ? denotes PRINT, as it does in QBasic.
    - ' is a code literal in QBIC: everything until the ` is not parsed, but
      passed on to QBasic.
    - In this case, we want a literal ; to appear after PRINT X$. This suppresses
      QBasic's normal line-break after PRINT. This needs to be a code literal
      because it is the command to read a String var from the command Line in QBIC.
[u|?]     FOR EACH meter above the ground, print a newline
u=u-1     Descent 1 meter
?@____|`  Print the LHS of the landing strip
+@     `  plus 5 spaces
+_fC|     plus the LHS reversed.
\         ELSE - touchdown!
_x        Terminate the program (effectively escape the infinite DO-loop)
    - the _x command has an interesting property: ULX, or Upper/Lowercase Extensibility.
      Writing this command with an uppercase _X does something similar, yet different.
      The _x command terminates, and prints everything found between _x and | before
      quitting. Uppercase _X does not look for |, but only prints something if it is
      followed by a character in the ranges a-z and A-Z - it prints the contents of
      that variable.
C+B+_fC   But before we quit, print C$ (the LHS of the landing strip) and the plane,
          and the LHS flipped.

---- #4 QBIC has left the building
- Did I say _x looks for a | ? Well, that gets added implicitly by QBIC at the end of
  the program, or when one ( ']' ) or all ( '}' ) opened language constructs are closed.
- Also, all still opened language constructs are automatically closed at EOF.
- Had we stored anything in Z$, that would also be printed at this time.

8th, 177 172 bytes
: f 5 >r 5 repeat over " " swap s:* . "--O--" . ' cr r> times "____|     |____\n\n" . over 5 n:cmp rot swap n:- swap n:1- dup >r while "____|--O--|____\n" . 2drop r> drop ;

The word f expects an integer between 0 and 10.
Usage
4 f

Explanation
: f \ n --
  5 >r     \ Push vertical distance from airport to r-stack
  5 repeat
    \ Print plane
    over " " swap s:* . "--O--" .
    \ Print airport
    ' cr r> times "____|     |____\n\n" .
    \ Now on the stack we have:
    \ distanceFromLeftSide distanceFromAirport
    over      \ Put distance from left side on TOS
    5 n:cmp   \ Compare left distance and 5. Return
              \ -1 if a<b, 0 if a=b and 1 if a>b
    rot       \ Put distance from left side on TOS
    swap n:-  \ Compute new distance from left side
    swap n:1- \ Decrement distance from airport
    dup >r    \ Push new airport-distance on the r-stack
  while
  "____|--O--|____\n" .  \ Print final step
  2drop r> drop          \ Empty s-stack and r-stack
;

Mathematica, 111 bytes
If[#<1,"____|--O--|____"," "~Table~#2<>"--O--"<>"
"~Table~#<>"____|     |____

"<>#0[#-1,#2+#2~Order~5]]&[5,#]&

Anonymous function. Takes a number as input and returns a string as output. Could probably be golfed further.

SmileBASIC, 109 105 bytes
G$="_"*4INPUT X
FOR I=0TO 4?" "*X;"--O--";CHR$(10)*(4-I)?G$;"|     |";G$X=X-SGN(X-5)?NEXT?G$;"|--O--|";G$

PHP 7, 139 bytes
still awfully long
for($x=$argv[1],$d=6;$d--;$x+=5<=>$x)for($i=$p=-1;$i++<$d;print"$s
")for($s=$i<$d?" ":"____|     |____
";!$i&++$p<5;)$s[$x+$p]="--O--"[$p];

takes input from command line argument; run with -r.
breakdown
for($x=$argv[1],                        // take input
    $y=6;$y--;                          // loop height from 5 to 0
    $x+=5<=>$x)                             // post increment/decrement horizontal position
    for($i=$p=-1;$i++<$y;                   // loop $i from 0 to height
        print"$s\n")                            // 3. print
        for($s=$i<$y?" ":"____|     |____\n";   // 1. template=empty or runway+newline
            !$i&++$p<5;)$s[$x+$p]="--O--"[$p];  // 2. if $i=0, paint plane

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Longest Cycle in a Graph
Given a directed graph, output the longest cycle.
Rules

Any reasonable input format is allowed (e.g. list of edges, connectivity matrix).
The labels are not important, so you may impose any restrictions on the labels that you need and/or desire, so long as they do not contain additional information not given in the input (e.g. you can't require that the nodes in cycles are labeled with integers, and other nodes are labeled with alphabetic strings).
A cycle is a sequence of nodes that are all connected, and no node is repeated, other than the node that is the start and end of the cycle ([1, 2, 3, 1] is a cycle, but [1, 2, 3, 2, 1] is not).
If the graph is acyclic, the longest cycle has length 0, and thus should yield an empty output (e.g. empty list, no output at all).
Repeating the first node at the end of the list of nodes in the cycle is optional ([1, 2, 3, 1] and [1, 2, 3] denote the same cycle).
If there are multiple cycles of the same length, any one or all of them may be output.
Builtins are allowed, but if your solution uses one, you are encouraged to include an alternate solution that does not use trivializing builtins (e.g. a builtin that outputs all cycles). However, the alternate solution will not count towards your score at all, so it is entirely optional.

Test Cases
In these test cases, input is given as a list of edges (where the first element is the source node and the second element is the destination node), and the output is a list of nodes without repetition of the first/last node.
[(0, 0), (0, 1)] -> [0]
[(0, 1), (1, 2)] -> []
[(0, 1), (1, 0)] -> [0, 1]
[(0, 1), (1, 2), (1, 3), (2, 4), (4, 5), (5, 1)] -> [1, 2, 4, 5]
[(0, 1), (0, 2), (1, 3), (2, 4), (3, 0), (4, 6), (6, 8), (8, 0)] -> [0, 2, 4, 6, 8]
[(0, 0), (0, 8), (0, 2), (0, 3), (0, 9), (1, 0), (1, 1), (1, 6), (1, 7), (1, 8), (1, 9), (2, 1), (2, 3), (2, 4), (2, 5), (3, 8), (3, 1), (3, 6), (3, 7), (4, 1), (4, 3), (4, 4), (4, 5), (4, 6), (4, 8), (5, 0), (5, 8), (5, 4), (6, 0), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (6, 6), (6, 7), (6, 9), (7, 0), (7, 1), (7, 2), (7, 3), (7, 4), (7, 5), (7, 8), (7, 9), (8, 0), (8, 1), (8, 2), (8, 5), (8, 9), (9, 1), (9, 2), (9, 3), (9, 4), (9, 5), (9, 6)] -> [0, 9, 6, 7, 8, 2, 5, 4, 3, 1]
[(0, 0), (0, 2), (0, 4), (0, 5), (0, 7), (0, 9), (0, 11), (1, 2), (1, 4), (1, 5), (1, 8), (1, 9), (1, 10), (2, 0), (2, 1), (2, 3), (2, 4), (2, 5), (2, 6), (3, 0), (3, 1), (3, 5), (3, 6), (3, 7), (3, 8), (3, 9), (3, 11), (4, 1), (4, 3), (4, 7), (4, 8), (4, 9), (4, 10), (4, 11), (5, 0), (5, 4), (5, 6), (5, 7), (5, 8), (5, 11), (6, 0), (6, 8), (6, 10), (6, 3), (6, 9), (7, 8), (7, 9), (7, 2), (7, 4), (7, 5), (8, 8), (8, 9), (8, 2), (8, 4), (8, 7), (9, 0), (9, 1), (9, 2), (9, 3), (9, 6), (9, 10), (9, 11), (10, 8), (10, 3), (10, 5), (10, 6), (11, 2), (11, 4), (11, 5), (11, 9), (11, 10), (11, 11)] -> [0, 11, 10, 6, 9, 3, 8, 7, 5, 4, 1, 2]

In all your examples, your output starts with the node with the smallest index. Is this a requirement?

@Dada No, that's just a coincidence with the test cases. The output should start (and optionally end) with the first node in the cycle.

You should pick a format, with endpoint or without is arbitrary and adds nothing to the challenge.

@carusocomputing I disagree. The last node is implicit if left off (since it's the same as the first node). Allowing the choice of whether or not to repeat the first node allows more freedom in golfing.

@Mego I thought you meant you had to handle either, then reread it and realized that that's the output format, not the input format.

@Dada Yep, that was a relic from the original version of the challenge (which was simply to output the length, rather than the cycle).

Related, kinda.

Mathematica, 80 58 bytes
Saved a whopping 22 bytes thanks to JungHwan Min
(FindCycle[#,∞,All]/.{}->{Cases[#,v_v_]})[[-1,;;,1]]&

 is the three byte private use character U+F3D5 representing \[DirectedEdge]. Pure function with first argument # expected to be a list of directed edges. Finds All cycles of length at most Infinity in Graph@#, then replaces the empty list with the list of self-loops. Cycles are represented as lists of edges and sorted by length, so we take the last such cycle, then from all of its edges we take the first argument so that we get a list of vertices in the specified output format.
If only Mathematica treated loops as a cycle of length 1 (AcyclicGraphQ @ CycleGraph[1, DirectedEdges -> True] gives True, seriously), then we could save another 26 bytes:
FindCycle[#,∞,All][[-1,;;,1]]&

You won't need MaximalBy because the result of FindCycle is already sorted by length (the last element is the longest). Also, the first argument of FindCycle can be a list of \[DirectedEdge] (instead of a Graph). Plus, you can use the 2-byte ;; (= 1;;-1) instead of the 3-byte All in Part to save a byte. -22 bytes (58 bytes): (FindCycle[#,∞,All]/.{}->{Cases[#,v_v_]})[[-1,;;,1]]&

Haskell, 157 154 150 bytes
import Data.List
g#l=nub[last$(e:d):[d|p==last q||e`elem`init d]|d@(p:q)<-l,[e,f]<-g,p==f]
h g=snd$maximum$((,)=<<length)<$>[]:until((==)=<<(g#))(g#)g

Try it online!
Thanks @Laikoni and @Zgrab for saving a bunch of bytes!
This is a very inefficient program:
The first function # takes a list of paths l (a list of lists of numbers) and tries to extend the elements of l by prepending every possible edge (a list of length 2) of g to each element of l.  This happens only if the element of l isn't already a cycle and if the new node that would be prepended is not already contained in the element of l. If it is already a cycle, we do not prepend anything but add it again to the new list of paths, if we can extend it, we add the extended path to the new list, otherwise we don't add it to the new list.
Now the function h repeatedly tries to extend those paths (starting with the list of edges itself) until we reach a fixed point, i.e. we cannot extend any path any further. At this point we only have cycles in our list. Then it is just a matter of picking the longest cycle. Obviously the cycles appear multiple times in this list since every possible cyclic rotation of a cycle is again a cycle.

You can drop the parentheses in (p:q)<-l.

And using <$> instead of map should save another byte in ((,)=<<length)<$>[]:.

@Laikoni Thank you very much!

You have an extra space after the final line. Also, doing d@(p:q)<-l saves some bytes.

Oh, the d@(p:q) is really nice, thank you for showing me!

JavaScript (ES6), 173 163 156 145 139 bytes
Saved 5 bytes thanks to @Neil
f=(a,m,b=[])=>a.map(z=>!([x,y]=z,m&&x-m.slice(-1))&&b.length in(c=(n=m||[x],q=n.indexOf(y))?~q?b:f(a.filter(q=>q!=z),[...n,y]):n)?b=c:0)&&b

Test snippet

f=(a,m,b=[])=>a.map(z=>!([x,y]=z,m&&x-m.slice(-1))&&b.length in(c=(n=m||[x],q=n.indexOf(y))?~q?b:f(a.filter(q=>q!=z),[...n,y]):n)?b=c:0)&&b

g=a=>console.log("Input:",JSON.stringify(a),"Output:",JSON.stringify(f(a)))

g([[0,0]])
g([[0,1],[1,2]])
g([[0,1],[1,0]])
g([[0,1],[1,2],[2,0]])
g([[0,1],[1,2],[1,3],[2,4],[4,5],[5,1]])
g([[0,1],[0,2],[1,3],[2,4],[3,0],[4,6],[6,8],[8,0]])

Surely switching to a plain old map saves you a couple of bytes?

@Neil It'd have to be .filter().map(), so almost certainly not. The switch saved me 10 bytes (though it wasn't as fully golfed as it is now)

I don't see you using the result of the comprehension, so instead of using a.filter(z=>!e).map(z=>d) you can use a.map(z=>e?0:d).

You're right, I can combine everything to save 5 bytes. And I just realized I don't need a+a? either :-)

Could the downvoter please explain what's wrong? Does it produce incorrect outputs?

Pyth, 20 bytes
eMefqhMT.>{eMT1s.pMy

Test suite
Takes a list of edges, like in the examples.
Explanation:
eMefqhMT.>{eMT1s.pMy
eMefqhMT.>{eMT1s.pMyQ    Variable introduction
                   yQ    Take all subsets of the input, ordered by length
                .pM      Reorder the subsets in all possible ways
               s         Flatten
                         (This should be a built in, I'm going to make it one.)
   f                     Filter on (This tests that we've found a cycle)
    qhMT                 The list of first elements of edges equals
           eMT           The last elements
         .>   1          Rotated right by 1
        {                Deduplicated (ensures no repeats, which would not be a
                         simple cycle)
  e                      Take the last element, which will be the longest one.
eM                       Take the last element of each edge, output.

Bash + bsdutils, 129 bytes
sed 's/^\(.*\) \1$/x \1 \1 x/'|sort|(tsort -l>&-)|&tr c\\n '
 '|sed 's/x //g'|awk 'm<NF{m=NF;gsub(/[^0-9 ] ?/,"");print}'|tail -1

tsort does all the heavy lifting, but its output format is rather unique and it doesn't detect cycles of length 1. Note that this doesn't work with GNU tsort.
Verification
--- t1 ---
0
--- t2 ---
--- t3 ---
0 1
--- t4 ---
1 2 4 5
--- t5 ---
0 2 4 6 8
--- t6 ---
0 2 1 6 3 7 4 8 9 5
--- t7 ---
0 11 10 3 1 2 4 7 5 8 9 6

Haskell, 109 108 bytes
import Data.List
f g=last$[]:[b|n<-[1..length g],e:c<-mapM(\_->g)[1..n],b<-[snd<$>e:c],b==nub(fst<$>c++[e])]

A brute force solution: generate all lists of edges of increasing lengths until the length of the input, keep those that are cycles, return the last one.
Takes the graph in the format [(1,2),(2,3),(2,4),(4,1)].
Try it online!
Explanation
f g=                    -- Define function f on input g as
  last$                 -- the last element of the following list
  []:                   -- (or [], if the list is empty):
  [b|                   --  lists of vertices b where
   n<-[1..length g],    --  n is between 1 and length of input,
   e:c<-                --  list of edges with head e and tail c is drawn from
    mapM(\_->g)[1..n],  --  all possible ways of choosing n edges from g,
   b<-[snd<$>e:c],      --  b is the list of second elements in e:c,
   b==                  --  and b equals
    nub(fst<$>c++[e])]  --  the de-duplicated list of first elements
                        --  in the cyclic shift of e:c.

It took now a while until I finally understood what is going on, the part for checking for paths/cycles is really clever, I am amazed!

@flawr Thanks! Well, it appears that isaacg used essentially the same algorithm before me.

MATLAB, 291 260 bytes
Takes an adjecency matrix A where an edge (i,j) is denoted by a 1 in A(i,j), and A is zero in all other entries. The output is a list of a longest cycle. The list is empty if there is no cycle at all, and the list includes start and endpoint if there is a cycle. It uses 1-based indexing.
This solution does not use any built-in functions related to graphs.
function c=f(A);N=size(A,1);E=eye(N);c=[];for j=1:N;l=g(j);if numel(l)>numel(c);c=l;end;end;function p=g(p)if ~any(find(p(2:end)==p(1)))e=E(p(end),:)Q=find(e*A)k=[];for q=Q;if ~ismember(q,p(2:end))n=g([p,q]);if numel(n)>numel(k);k=n;end;end;end;p=k;end;end;end

Unfortunately this does not run in TryItOnline as it uses a function within a function, which is recursive. A little bit of modification allows you to try it on octave-online.net.
For the very last test case I found an alternative longest cycle [0 2 1 4 3 5 7 8 9 11 10 6 0] (this notation uses 0-based indexing)
Explanation
The basic approach here is that we perform a BFS from every node and take care that we do not visit any of the intermediate nodes again except the start node. With that idea we can collect all possible cycles, and easily pick the longest one.
function c=f(A);
N=size(A,1);
E=eye(N);
c=[]; % current longest cycle
for j=1:N;                                      % iterate over all nodes
    l=getLongestCycle(j);                       % search the longest cycle through the current node
    if numel(l)>numel(c);                       % if we find a longer cycle, update our current longest cycle
        c=l;
    end;

end;

    function p=getLongestCycle(p);              % get longest cycle from p(1) using recursion
        if ~any(find(p(2:end)==p(1)));          % if we just found a cycle, return the cycle do nothing else, OTHERWISE:
            e=E(p(end),:);                      % from the last node, compute all outgoing edges
            Q=find(e*A);
            k=[];
            for q=Q;                            % iterate over all outogoin edges
                if ~ismember(q,p(2:end));       % if we haven't already visited this edge,
                    n=getLongestCycle([p,q]);   % recursively search from the end node of this edge
                    if numel(n)>numel(k);       % if this results in a longer cycle, update our current longest cycle
                        k=n;
                    end;
                end;
            end;
            p=k;
        end;
    end;
end

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/