text:
Collatz Conjecture (OEIS A006577)
This is the Collatz Conjecture (OEIS A006577):

Start with an integer n > 1.
Repeat the following steps:

If n is even, divide it by 2.
If n is odd, multiply it by 3 and add 1.

It is proven that for all positive integers up to 5 * 260, or about 5764000000000000000, n will eventually become 1.
Your task is to find out how many iterations it takes (of halving or tripling-plus-one) to reach 1.
Relevant xkcd :)
Rules:

Shortest code wins.
If a number < 2 is input, or a non-integer, or a non-number, output does not matter.

Test cases
2  -> 1
16 -> 4
5  -> 5
7  -> 16

GolfScript, 24 23 21 20 18 chars
~{(}{3*).2%6\?/}/,

Assumes input on stdin. Online test

1+ is special-cased as ).

@PeterTaylor of course, forgot about that ;)

There are a couple of replacements which tie for length and might be of interest. One is to replace the loop body with .5*)).1&*+2/; the other is to work with x-1 rather than x which turns the unfold into ({}{.2%!{)6*}*2/}/

Nice work!

@Peter: The  don't work in comments. Use this instead.

Or this.

Well, I doubt anyone can get any shorter than this, so I'm accepting it. Good job!

C - 50 47 characters
Poor little C unfortunately requires an awful amount of code for basic I/O, so shorting all that down has made the UI slightly unintuitive.
b;main(a){return~-a?b++,main(a&1?3*a+1:a/2):b;}

Compile it with for example gcc -o 1 collatz.c. The input is in unary with space-separated digits, and you will find the answer in the exit code. An example with the number 17:
$> ./1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
$> echo $?
12
$>

return~-a? saves 1. Also moving b++ to the ? case should save b--.

Hehe you're bending the rules so much :P +1 for creativity and using a language not usually used to golf

Thank you ugoren! I must have been drunk when writing it. :)

@Doorknob Yeah I wish C was more popular in code golfing.

FRACTRAN, 8 fractions (45 bytes)
$$\frac{5120}{33}, \frac{15}{11}, \frac{22}{105}, \frac{33}{560}, \frac{13}{5}, \frac{3}{2}, \frac{7}{9}, \frac{11}{7}$$
Takes input as \$3^n\$; halts at \$3 \cdot 13^m\$ for a sequence with \$m\$ iterations.
Try it online!
How it works
If the current state is \$3^n \cdot 13^m\$, if \$n = 1\$, the program halts immediately; if \$n = 2k\$ is even, we have
$$\begin{multline*}3^{2k} \cdot 13^m
\xrightarrow{\left(\frac{7}{9}\right)^k}
7^k \cdot 13^m
\xrightarrow{\frac{11}{7}}
7^{k - 1}\cdot 11 \cdot 13^m
\xrightarrow{\frac{15}{11}}
3 \cdot 5 \cdot 7^{k - 1} \cdot 13^m
\\
\xrightarrow{\left(\frac{22}{105} \cdot \frac{15}{11}\right)^{k - 1}}
2^{k - 1} \cdot 3 \cdot 5 \cdot 13^m
\xrightarrow{\frac{13}{5}}
2^{k - 1} \cdot 3 \cdot 13^{m + 1}
\xrightarrow{\left(\frac{3}{2}\right)^{k - 1}}
3^k \cdot 13^{m + 1};\end{multline*}$$
and if \$n = 2k + 1\$ is odd, we have
$$\begin{multline*}
3^{2k + 1} \cdot 13^m
\xrightarrow{\left(\frac{7}{9}\right)^k}
3 \cdot 7^k \cdot 13^m
\xrightarrow{\frac{11}{7}}
3 \cdot 7^{k - 1} \cdot 11 \cdot 13^m
\xrightarrow{\frac{5120}{33}}
2^{10} \cdot 5 \cdot 7^{k - 1} \cdot 13^m
\\
\xrightarrow{\left(\frac{33}{560} \cdot \frac{5120}{33}\right)^{k - 1}}
2^{6k + 4} \cdot 5 \cdot 13^m
\xrightarrow{\frac{13}{5}}
2^{6k + 4} \cdot 13^{m + 1}
\xrightarrow{\left(\frac{3}{2}\right)^{6k + 4}}
3^{6k + 4} \cdot 13^{m + 1},\end{multline*}$$
where \$6k + 4 = 3n + 1\$.

What a competitive solution (byte-count-wise) for such an unwieldy, syntax-limited language.

If you use your Collatz program from another challenge, you can get another 8-fraction solution that fits in 41 bytes. https://gist.github.com/kmill/9462894fe99d9e93733e788585f45444

What an interesting language

Perl 34 (+1) chars
$\++,$_*=$_&1?3+1/$_:.5while$_>1}{

Abusing $\ for final output, as per usual. Run with the -p command line option, input is taken from stdin.
Saved one byte due to Elias Van Ootegem. Specifically, the observeration that the following two are equivalent:
$_=$_*3+1
$_*=3+1/$_

Although one byte longer, it saves two bytes by shortening $_/2 to just .5.
Sample usage:
$ echo 176 | perl -p collatz.pl
18

PHP 54 bytes
<?for(;1<$n=&$argv[1];$c++)$n=$n&1?$n*3+1:$n/2;echo$c;

Javascript's archnemesis for the Wooden Spoon Award seems to have fallen a bit short in this challenge. There's not a whole lot of room for creativity with this problem, though. Input is taken as a command line argument.
Sample usage:
$ php collatz.php 176
18

Took me a while to figure out what the unmatched brackets are doing :)

Repeating $_ in the ternary seems wasteful, you can shave off another character by using *= like this: $\++,$_*=$_&1?3+1/$_:.5while$_>1}{. Multiplying by 1/$_ has the same effect as +1, so $_*=3+1/$_ works just fine

@EliasVanOotegem $_*=3+1/$_ is brilliant, thanks!

Mathematica (35)
If[#>1,#0@If[OddQ@#,3#+1,#/2]+1,0]&

Usage:
If[#>1,#0[If[OddQ@#,3#+1,#/2]]+1,0]&@16
>> 4

It's not a valid function, 10.3 complains about a rogue @ at the end

@ is calling the argument, I don't know why it was there, just a quick edit

Gotta be careful :)

This function has max recursion depth 1024. The first value for which it fails is 2610744987 because it needs 1050 steps. Try it online!

As I usually do, I will start the answers off with my own.
JavaScript, 46 44 chars (run on console)
for(n=prompt(),c=1;n>1;n=n%2?n*3+1:n/2,++c)c

What is the point of ~~prompt() if you said the output doesn't matter if it is a non-integer? You can save two characters by getting rid of ~~.

@Resorath Ah, forgot about JS's auto casting :P thanks

Java, 165, 156, 154,134,131,129,128,126 (verbose languages need some love too)
class a{public static void main(String[]a){for(int x=Short.valueOf(a[0]),y=0;x>1;x=x%2<1?x/2:x*3+1,System.out.println(++y));}}

All is done inside the for
for(int x=Short.valueOf(a[0]),y=0;x>1;x=x%2<1?x/2:x*3+1,System.out.println(++y))

That's freaking beautiful man. Thanks to Pater Taylor!!!, and the idea of using a for loop was stolen from ugoren
I replaced Integer for Short.

You can quite easily save the length of i(,++y). You can save two more by using < instead of ==.

@PeterTaylor you're right, my comparisons will be shorter with < , but I don't understand the part of the pre-increment

The two sides of your second ternary are structurally identical, so you can push the ternary into the first argument of the recursive call.

OH MY GOD THAT'S BRILLIANT

I know it has been about 3.5 years, but you can still golf it by 5 bytes: class a{public static void main(String[]a){for(int x=new Short(a[0]),y=0;x>1;System.out.println(++y))x=x%2<1?x/2:x*3+1;}} Changes made: 1) Replaced Short.valueOf(...) with new Short(...) for -4 bytes and 2) I've put the x=x%2<1?x/2:x*3+1; in the body of the for-loop to get rid of the comma for -1 byte.

In addition to my golfs in the comment above, you can change class a{public static void main to interface a{static void main (Java 8+) (-1 byte), and new Short can be new Byte (-1 byte).

Python repl, 48
I'm not convinced that there isn't a shorter expression than n=3*n+1;n/=1+n%2*5;.  I probably found a dozen different expressions of all the same length...
i=0
n=input()
while~-n:n=3*n+1;n/=1+n%2*5;i+=1
i

edit: I've found another solution that will never contend, but is too fun not to share.
s='s'
i=s
n=i*input()
while 1:
 while n==n[::2]+n[::2]:i+=s;n=n[::2]
 if n==s:i.rindex(s);break
 n=3*n+s
 i+=s

My brain hurts now.

@daniero the second solution is just for you.

Oh wow. I'm honored!

(n//2,n*3+1)[n%2] is shorter.

The OP didn't specify, but I would put print there, or remove that i at the end—it's basically a no-op.

Is this for Python2.7? I get bad operand type for unary -: 'str' in Python 3.5.1

@Evpok wouldn't n/2 work as well as we know it is even?

@george It would return a float anyway

Rebmu: 28
u[++jE1 AeEV?a[d2A][a1M3a]]j

On a problem this brief and mathy, GolfScript will likely win by some percent against Rebmu (if it's not required to say, read files from the internet or generate JPG files).  Yet I think most would agree the logic of the Golfscript is nowhere near as easy to follow, and the total executable stack running it is bigger.
Although Rebol's own creator Carl Sassenrath told me he found Rebmu "unreadable", he is busy, and hasn't time to really practice the pig-latin-like transformation via unmushing.  This really is merely transformed to:
u [
    ++ j
    e1 a: e ev? a [
        d2 a
    ] [
        a1 m3 a
    ]
]
j

Note that the space was required to get an a: instead of an a.  This is a "set-word!" and the evaluator notices that symbol type to trigger assignment.
If it were written in unabbreviated (yet awkwardly-written Rebol), you'd get:
until [
    ++ j
    1 == a: either even? a [
        divide a 2
    ] [
        add 1 multiply 3 a
    ]
 ]
 j

Rebol, like Ruby, evaluates blocks to their last value.  The UNTIL loop is a curious form of loop that takes no loop condition, it just stops looping when its block evaluates to something not FALSE or NONE.  So at the point that 1 == the result of assigning A (the argument to rebmu) to the result of the Collatz conditional (either is an IF-ELSE which evaluates to the branch it chooses)... the loop breaks.
J and K are initialized to integer value zero in Rebmu.  And as aforementioned, the whole thing evaluates to the last value.  So a J reference at the end of the program means you get the number of iterations.
Usage:
>> rebmu/args [u[++jE1 AeEV?a[d2A][a1M3a]]j] 16
== 4

Not trying to be mean, just pointing out that the website changed to rebmu.hostilefork.com :)

Brachylog, 16 bytes
1b|{/₂ℕ|×₃+₁}↰+₁

Try it online!
Explanation
         Either:
  1        The input is 1.
  b        In which case we unify the output with 0 by beheading the 1
           (which removes the leading digit of the 1, and an "empty integer"
           is the same as zero).
|        Or:
  {        This inline predicate evaluates a single Collatz step on the input.
           Either:
    /₂       Divide the input by 2.
    ℕ        And ensure that the result is a natural number (which is
             equivalent to asserting that the input was even).
  |        Or:
    ×₃+₁     Multiply the input by 3 and add 1.
  }
  ↰        Recursively call the predicate on this result.
  +₁       And add one to the output of the recursive call.

An alternative solution at the same byte count:
;.{/₂ℕ|×₃+₁}ⁱ⁾1∧

Try it online!
;.          The output of this is a pair [X,I] where X is the input and
            I will be unified with the output.
{/₂ℕ|×₃+₁}  This is the Collatz step predicate we've also used above.
ⁱ⁾          We iterate this predicate I times on X. Since we haven't actually
            specified I, it is still a free variable that Brachylog can backtrack
            over and it will keep adding on iterations until the next
            constraint can be satisfied.
1           Require the result of the iteration to be 1. Once this is
            satisfied, the output variable will have been unified with
            the minimum number of iterations to get here.
∧           This AND is just used to prevent the 1 from being implicitly
            unified with the output variable as well.

J, 30 characters
<:#-:`(1+3&*)`]@.(2&|+1&=)^:a:

Turned out quite a bit longer than desired
usage:
   <:#-:`(1+3&*)`]@.(2&|+1&=)^:a:2
1
   <:#-:`(1+3&*)`]@.(2&|+1&=)^:a:16
4
   <:#-:`(1+3&*)`]@.(2&|+1&=)^:a:5
5
   <:#-:`(1+3&*)`]@.(2&|+1&=)^:a:7
16
   <:#-:`(1+3&*)`]@.(2&|+1&=)^:a:27
111

-:`(1+3&*)`] is a gerund composed of three verbs, used on three occasions. -: means "halve", (1+3&*) or (1+3*]) encodes the multiplication step and ] (identity) aids termination.

2&|+1&= forms an index to the gerund. literally, "the remainder after division by two plus whether it equals one".

#verb^:a: iterates the function until the result is stable (here, forced explicitly), while collecting the steps, then counts them. Stolen from @JB. <: decrements the step count by one to align with the question requirements.

Whenever I see a J submission, I count the smilies. This one does pretty well: <:, #-:, :\(, &*), =), )^:`.

@primo nice; want their explanation? :-) <: means "decrement" or "less or equal", # means "count of" or "n times", -: means "halve" or "epsilon-equality", :`( mean in turn the end of said "halve", the tie between two verbs in a gerund and a left parenthesis (used for grouping). &*) means "sth. bonded to the multiplication" (3 bonded with multiplication creates the "times three" operator) and the end of grouping. = performs equality checking or, in the unary sense, self-classification. ^: is the power conjunction (verb iteration). Since a lot of J verbs end with a colon, ... :-)

Years later... Improved loop block: '-&2#(>&1*-:+2&|*+:+>:@-:)^:a:' -> -1 char. :P

More years later... <:#a:2&(<*|+|6&*%~) 19 bytes (-11)

80386 assembly, 16 bytes
This example uses AT&T syntax and the fastcall calling convention, the argument goes into ecx:
collatz:
        or $-1,%eax              # 3 bytes, eax = -1;
.Loop:  inc %eax                 # 1 byte,  eax += 1;
        lea 1(%ecx,%ecx,2),%edx  # 4 bytes, edx = 3*ecx + 1;
        shr %ecx                 # 2 bytes, CF = ecx & 1;
                                 #          ecx /= 2;
                                 #          ZF = ecx == 0;
        cmovc %edx,%ecx          # 3 bytes, if (CF) ecx = edx;
        jnz .Loop                # 2 bytes, if (!ZF) goto .Loop;
        ret                      # 1 byte,  return (eax);

Here are the resulting 16 bytes of machine code:
83 c8 ff 40 8d 54 49 01 d1 e9 0f 42 ca 75 f4 c3

FRACTRAN, 24 fractions
Uses 180 bytes, for the more conventional counters...
68/13, 133/102, 341/51, 115/17, 17/19, 87/161, 17/23, 23/29, 53/93,
26973/217, 410/259, 43/111, 976/37, 37/41, 329/215, 37/43, 43/47,
118/265, 1/53, 53/59, 67/305, 1/61, 61/67, 117/4

Try it online!
Explanation
Am a bit lazy to add an explanation now; happy to do so if it gets attention/upvotes! However, I do have some notes for when I first wrote up the Collatz Conjecture code which you can run here. It's almost the same, but the TIO command line arguments are set to print every number in the sequence along the way, which makes it less of a blackbox!
State Diagrams for COLLATZGAME
Here are the state diagrams, for which I used Conway's original notation which he presents in this article.

Change Made
The above is simply to calculate the Collatz sequence for n given an input of the form 2^n. The only change I made to also keep count of the steps taken was to make the 1/3 from states Q -> D into an 11/3, 11 being the smallest unused prime. This fraction is only executed once for every number in the sequence; it's the state that figures out whether the number is even or odd to figure out what's next. Therefore, the 11 prime register is incremented once per number in the sequence, except one, yielding the number of steps.
Note
I simply encoded the state diagram as below and wrote an interpreter which did the dirty work. However, the work done to convert a state diagram to FRACTRAN is also detailed in Conway's article above:

A: 9/4 -> T
T: 4/1 -> Q
Q: 7/6*, 11/3 -> D, 5/1 -> R
R: 3/7*|Q
D: 1/3 -> E, 729/7 -> M
M: 10/7*, 1/3 -> N, 16/1 -> O
N: 7/5*|M
E: 2/5*|A
O: 1/5*|A

APL (31)
A←0⋄A⊣{2⊤⍵:1+3×⍵⋄⍵÷2}⍣{⍺=A+←1}⎕

old answer, yet, 27: {1=⍵:0⋄2|⍵:1+∇1+3×⍵⋄1+∇⍵÷2}

{1=⍵:0⋄1+∇⊃⍵⌽0 1+.5 3×⍵}

Gambit scheme, 106 98 characters, 40 parentheses
(let((f(lambda(x)(cond((= x 1) 0)((odd? x)(+ 1(f(+ 1(* 3 x)))))(else(+ 1(f(/ x 2))))))))(f(read)))

91 89 chars with define directly
(define(f x)(cond((= x 1)0)((odd? x)(+ 1(f(+ 1(* 3 x)))))(else(+ 1(f(/ x 2))))))(f(read))

I haven't been around for a long time, but I have notice that usually people post 1 answer per programming language.

Sorry, I wasn't aware of that :)

Edited to remove the Python one.

Not true! People tend to post one answer per programming language, but that's because they're trying not to directly compete with someone else with a shorter answer. But nobody's going to complain if you post a different answer in the same language.

@breadbox not true. I post one answer per language if each solution is interesting by itself compared to the other. If both solutions are each as interesting as them both together (the same algorithm, no interesting language tricks), I post them as one. Normally I don't post multiple solutions because I choose a language first, then solve the problem in that language - then I'm usually too lazy to write the same in a different language - or I embark on a journey to learn yet another programming language.

Interesting, but it doesn't contradict my point, which is that there's no reason to not post a solution just because someone else already has one in that language.

Python 2, 68 58 54 52 bytes
f=lambda n:1+(n-2and f((n/2,3*n+1)[n%2]));f(input())

Thanks to @Bakuriu and @boothby for the tips :)

You can use n%2and 3*n+1or n/2 to save 5 characters. Also in python2 you can remove the call to int, reducing the size to 58 bytes.

Oh, you can even get shorter than that: [n/2,3*n+1][n%2].

That is nifty !

Is this python 2.7? I get an error in Python 3.5.1? unsupported operand type(s) for -: 'str' and 'int'

@george Yeah, this is Python 2.

PowerShell: 77 74 71 70 61
Golfed code:
for($i=(read-host);$i-ne1;$x++){$i=(($i/2),(3*$i+1))[$i%2]}$x

Notes:
I originally tried taking the user input without forcing it to an integer, but that broke in an interesting way. Any odd inputs would process inaccurately, but even inputs would work fine. It took me a minute to realize what was going on.
When performing multiplication or addition, PowerShell treats un-typed input as a string first. So, '5'*3+1 becomes '5551' instead of 16. The even inputs behaved fine because PowerShell doesn't have a default action for division against strings. Even the even inputs which would progress through odd numbers worked fine because, by the time PowerShell got to an odd number in the loop, the variable was already forced to an integer by the math operations anyway.

Thanks to Danko Durbic for pointing out I could just invert the multiplication operation, and not have to cast read-host to int since PowerShell bases its operations on the first object.

PowerShell Golfer's Tip: For some scenarios, like this one, switch beats if/else. Here, the difference was 2 characters.

Protip courtesy of Danko Durbic: For this particular scenario, an array can be used instead of switch, to save 8 more characters!

There's no error checking for non-integer values, or integers less than two.
If you'd like to audit the script, put ;$i just before the last close brace in the script.
I'm not sure exactly how well PowerShell handles numbers that progress into very large values, but I expect accuracy is lost at some point. Unfortunately, I also expect there's not much that can be done about that without seriously bloating the script.

Ungolfed code, with comments:
# Start for loop to run Collatz algorithm.
# Store user input in $i.
# Run until $i reaches 1.
# Increment a counter, $x, with each run.
for($i=(read-host);$i-ne1;$x++)
{
    # New $i is defined based on an array element derived from old $i.
    $i=(
        # Array element 0 is the even numbers operation.
        ($i/2),
        # Array element 1 is the odd numbers operation.
        (3*$i+1)
    # Array element that defines the new $i is selected by $i%2.
    )[$i%2]
}

# Output $x when the loop is done.
$x

# Variable cleanup. Don't include in golfed code.
rv x,i

Test cases:
Below are some samples with auditing enabled. I've also edited the output some for clarity, by adding labels to the input and final count and putting in spacing to set apart the Collatz values.
---
Input: 2

1

Steps: 1

---
Input: 16

8
4
2
1

Steps: 4

---
Input: 5

16
8
4
2
1

Steps: 5

---
Input: 7

22
11
34
17
52
26
13
40
20
10
5
16
8
4
2
1

Steps: 16

---
Input: 42

21
64
32
16
8
4
2
1

Steps: 8

---
Input: 14

7
22
11
34
17
52
26
13
40
20
10
5
16
8
4
2
1

Steps: 17

---
Input: 197

592
296
148
74
37
112
56
28
14
7
22
11
34
17
52
26
13
40
20
10
5
16
8
4
2
1

Steps: 26

---
Input: 31

94
47
142
71
214
107
322
161
484
242
121
364
182
91
274
137
412
206
103
310
155
466
233
700
350
175
526
263
790
395
1186
593
1780
890
445
1336
668
334
167
502
251
754
377
1132
566
283
850
425
1276
638
319
958
479
1438
719
2158
1079
3238
1619
4858
2429
7288
3644
1822
911
2734
1367
4102
2051
6154
3077
9232
4616
2308
1154
577
1732
866
433
1300
650
325
976
488
244
122
61
184
92
46
23
70
35
106
53
160
80
40
20
10
5
16
8
4
2
1

Steps: 106

---
Input: 6174

3087
9262
4631
13894
6947
20842
10421
31264
15632
7816
3908
1954
977
2932
1466
733
2200
1100
550
275
826
413
1240
620
310
155
466
233
700
350
175
526
263
790
395
1186
593
1780
890
445
1336
668
334
167
502
251
754
377
1132
566
283
850
425
1276
638
319
958
479
1438
719
2158
1079
3238
1619
4858
2429
7288
3644
1822
911
2734
1367
4102
2051
6154
3077
9232
4616
2308
1154
577
1732
866
433
1300
650
325
976
488
244
122
61
184
92
46
23
70
35
106
53
160
80
40
20
10
5
16
8
4
2
1

Steps: 111

---
Input: 8008135

24024406
12012203
36036610
18018305
54054916
27027458
13513729
40541188
20270594
10135297
30405892
15202946
7601473
22804420
11402210
5701105
17103316
8551658
4275829
12827488
6413744
3206872
1603436
801718
400859
1202578
601289
1803868
901934
450967
1352902
676451
2029354
1014677
3044032
1522016
761008
380504
190252
95126
47563
142690
71345
214036
107018
53509
160528
80264
40132
20066
10033
30100
15050
7525
22576
11288
5644
2822
1411
4234
2117
6352
3176
1588
794
397
1192
596
298
149
448
224
112
56
28
14
7
22
11
34
17
52
26
13
40
20
10
5
16
8
4
2
1

Steps: 93
---

Interesting bits about the input numbers which are not from the question's test cases:

14 and 197 are Keith Numbers
31 is a Mersenne Prime
6174 is Kaprekar's Constant
And lastly, I just like 8008135. And Numberphile, obviously.

Nice! You can still shorten it somewhat, by replacing switch with $i=(($i/2),($i*3+1))[$i%2]

Also, you don't have to convert read-host to number - just change $i*3 to 3*$i.

An array instead of switch? Brilliant! And swapping $i*3 around - why didn't I think of that already?

param($i)for(;$i-ne1;$x++){$i=(($i/2),(3*$i+1))[$i%2]}$x - swap the read-host for a parameter, to get 56 bytes.  Try It Online link

Jelly, 12 bytes
×3‘$HḂ?ß0’?‘

Try it online!
How it works
×3‘$HḂ?ß0’?‘  Main link. Argument: n (integer)

     Ḃ?       Yield the last bit of n is 1:
   $            Evaluate the three links to the left as a monadic chain:
×3                Multiply n by 3.
  ‘               Increment the product by 1.
    H           Else, halve n.
         ’?   If n-1 is non-zero:
       ß        Recursively call the main link.
        0     Else, yield 0.
           ‘  Increment the result by 1.

brainfuck, 59 56 bytes
,-[<->[[>]+<[-<]>>]>[-<<[++>+<]>->]<<[+>+++<]<<+>>>]<<<.

Try it online! (Slightly modified for ease of use)
Input and output as character codes. This is more useful with arbitrarily sized cells, but can still work with small values in limited cell sizes.
How It Works
Tape Format:
Counter 0 Copy Number Binary...
^End           ^Start

,-[ Get input, decrement by 1 and start loop
  <->                  Initialises the copy of the value at -1
  [[>]+<[-<]>>]        Converts the input to binary while preserving a negative copy
  <+>>[-<<[++>+<]>->] If the last digit of the binary is 1 (n-1 is odd), divide by 2 and decrement
  <<[+>+++<]            If the last digit of the binary is 0 (n-1 is even), multiply by 3
  <<+>>>               Increment counter and end on n-1
]<<<.                 End loop and print counter

Jelly, 10 bytes
×3‘ƊHḂ?Ƭi2

Try it online!
How it works
×3‘ƊHḂ?Ƭi2    Main link (monad). Input: integer >= 2
      ?       Create a "ternary-if" function:
     Ḃ          If the input is odd,
×3‘Ɗ            compute 3*n+1;
    H           otherwise, halve it.
       Ƭ      Repeat until results are not unique; collect all results
        i2    Find one-based index of 2

Example: The result of ...Ƭ for input 5 is [5, 16, 8, 4, 2, 1]. The one-based index of 1 is 6, which is 1 higher than expected. So we choose the index of 2 (which is guaranteed to come right before 1) instead.

ngn/k, 21 bytes
#{(2|-2!x;1+3*x)2!x}\

I converted the operation to be x = max(2, x/2) so the sequence had a fixed point, and converges (\) handled the rest. # counts the number of steps, including the beginning.

i believe you could at least get that byte back through moving the x from both branches outside the conditional?

I found that I'd save more bytes if I reformatted the whole function

GolfScript (23 chars)
~{.1&{.3*)}*.2/.(}do;],

Online test

F# - 65 chars
let rec c n=function 1->n|i->c(n+1)(if i%2=0 then i/2 else i*3+1)

dc, 27 characters
Applying boothby's black magic:
?[d3*1+d2%5*1+/d1<x]dsxxkzp

I'm not really sure if I understand how - or that - it works.

Usage:

$ dc collatz.dc <<< 7
16

dc, 36 characters
My own creation; a somewhat more traditional approach, even tho I had to wrangle with the language a fair bit to overcome the lack of an else part to if statements:
?[2/2Q]se[dd2%[0=e3*1+]xd1<x]dsxxkzp

Internally it produces all numbers of the sequence and stores them on the stack, then pops the final 1 and displays the stack height.

Parity is not black magic.

No, but it's a very neat trick there! I have actually done similar stuff myself, I just didn't think about it in this case. What stumbled me for a second was the division, but I get it: You divide by six, reverting the first operation (*=3,+=1) with the second if the parity was wrong, and because of integer division the addition goes away too, and we've basically done /=2. Very clever :)

+1. I thought I was going to crush this challenge with dc, but only got as far as 40.  The I saw your 27 answer.  Oh well.

I hadn't seen this challenge, but blogged a while back about printing the Collatz sequence in dc. My approach is similar to yours but loses by a byte so I don't really see a reason to post it. However, when I was looking at mine to see how to easily go from printing each step to printing the number of steps, I spotted something that can golf a byte from yours...
Since the Collatz sequence will always go from 2 to 1, you can change your conditional to 2<x and get rid of the k. Just in case you want a byte back after four years. :D

Ruby 1.9, 49 characters
Rubyfied Valentin CLEMENT's Python answer, using the stabby lambda syntax. Sqeezed it into one statement for added unreadability.
(f=->n{n>1&&1+f[[n/2,3*n+1][n%2]]||0})[gets.to_i]

Some overhead because Ruby, unlike Python, is not happy about mixing numbers with booleans.

Retina, 43 bytes
11
2
(2+)1
$1$1$0$0$0$0
2.*
$0x
)`2
1
1?x
1

Takes input and prints output in unary.
Each line should go to its own file. 1 byte per extra file added to byte-count.
You can run the code as one file with the -s flag. E.g.:
> echo -n 1111111|retina -s collatz
1111111111111111

The algorithm is a loop of doing a Collatz step with the unary number and adding a new step-marker x at the end of the string if the number isn't 1.
When the loop ends with 1, we convert the markers to a unary number (removing the leading 1) which is the desired output.

Julia 0.6, 29 27 bytes
!n=n>1&&1+!(n%2>0?3n+1:n/2)

I can't seem to compile Julia 0.1 on my machine, so there's a chance this is non-competing.
Try it online!

><>, 27 26 23 bytes
\ln;
\::2%:@5*1+2,*+:2=?

Like the other ><> answers, this builds the sequence on the stack. Once the sequence reaches 2, the size of the stack is the number of steps taken.
Thanks to @Hohmannfan, saved 3 bytes by a very clever method of computing the next value directly. The formula used to calculate the next value in the sequence is:
$$f(n)=n\cdot\frac{5(n\bmod2)+1}{2}+(n\bmod2)$$
The fraction maps even numbers to 0.5, and odd numbers to 3. Multiplying by n and adding n%2 completes the calculation - no need to choose the next value at all!
Edit 2: Here's the pre-@Hohmannfan version:
\ln;
\:::3*1+@2,@2%?$~:2=?

The trick here is that both 3n+1 and n/2 are computed at each step in the sequence, and the one to be dropped from the sequence is chosen afterwards. This means that the code doesn't need to branch until 1 is reached, and the calculation of the sequence can live on one line of code.
Edit: Golfed off another character after realising that the only positive integer that can lead to 1 is 2. As the output of the program doesn't matter for input < 2, the sequence generation can end when 2 is reached, leaving the stack size being the exact number of steps required.
Previouser version:
\~ln;
\:::3*1+@2,@2%?$~:1=?

You can golf it to 23 if you unbranch the second line even more:
\::2%:@5*1+2,*+:2=?

Hexagony, 48 44 bytes
?(]$_)"){{?{*')}/&!/={:<$["/>&_(.<@2'%<>./>=

Try it online!
Expanded:
     ? ( ] $ _
    ) " ) { { ?
   { * ' ) } / &
  ! / = . { < $ [
 " / > & _ ( . < @
  2 ' % < > : / >
   = . . . . . .
    . . . . . .
     . . . . .

 Note that this fails on 1 for uhh... reasons. Honestly, I'm not really sure how this works anymore. All I know is that the code for odd numbers is run backwards for even numbers? Somehow?
The new version is much cleaner than the previous, but has a few more directionals in comparison and also ends in a divide-by-zero error. The only case it doesn't error is when it actually handles 1 correctly.

If a number < 2 is input ... output does not matter. :o)

@Sok Yep, that's why I posted it instead of going insane trying to fix that

Haskell, 39 38 bytes
saved 1 byte thanks to DLosc
f 2=1
f n=1+f(cycle[div n 2,n*3+1]!!n)
Attempt This Online!

Q,46
{i::0;{x>1}{i+:1;$[x mod 2;1+3*x;(_)x%2]}\x;i}

32 bytes with (#)1_(1<){(1+3*x;x%2)0=x mod 2}\

C, 70 69 chars
Quite simple, no tricks.
Reads input from stdin.
a;
main(b){
    for(scanf("%d",&b);b-1;b=b%2?b*3+1:b/2)a++;
    printf("%d",a);
}

C++ (51 48)
This is a recursive function that does this; input reading comes separately.
int c(n){return n==1?0:1+(n%2?c(n*3+1):c(n/2));}

I'm sure I can do some sort of "and/or" trick with the == 0 stuff, but I have no idea how.

You could remove the ==0 and swap the sides of the conditional

Also, no need to handle n==1 because I specified in the question that the number is always greater than 1

The problem is that n==1 is the base recursion case. Putting n==2 there wouldn't improve the score any.

Ah, then you could just replace it with this: return~-n? and swap the conditional sides

.n==1==n<2.

~-~! (No Comment) - 71 53
This language is obviously not the best for golfing since it lacks a large amount of native functionality, but that's the beauty of it.
'=|*;~~[*,~~~-~]*/~~|:''=|'''==~[*]'''='&''':''&*+~|:

First, set ''' to your input. The function '' can then be called with % as it's input and will return the answer, like so:
'''=~~~~~:''&%:
This will return ~~~~~. It actually works for n==1 (it loops forever with n==0).
As always with this language, untested.

Perl 6, 40 bytes
Recursive function method, as per Valentin CLEMENT and daniero: 40 characters
sub f(\n){n>1&&1+f n%2??3*n+1!!n/2}(get)

Lazy list method: 32 characters
+(get,{$_%2??$_*3+1!!$_/2}...^1)

JavaScript (ES6) - 29 Characters
f=x=>x>1?f(x%2?x*3+1:x/2)+1:0

Creates a function f which accepts a single argument and returns the number of iterations.
JavaScript - 31 Characters
for(c=0;n>1;n=n%2?n*3+1:n/2)++c

Assumes that the input is in the variable n and creates a variable c which contains the number of iterations (and will also output c to the console as its the last command).

28 bytes

><>, 28 bytes
:1=?v::2%?v2,
+c0.\l1-n;\3*1

This takes input from the stack, computes the different steps on the stack, then returns its size when 1 is reached.

Improved version by JoKing, 24 bytes :
:1=?\::2%b$.2,
3*1+\~ln;

That is one of the most beautiful snippets of ><> I have ever seen.

Hu, is it? Thanks ! You might like my FizzBuzz one then, it's got a few control-flow tricks I was proud of.

Given the input can't be zero, you don't need to do the is one check when doing triple plus one, and therefore skip the jump entirely, saving three bytes. Then one more byte through shortening the output and using a jump instead of a conditional. Try it online!

@JoKing thanks, I appreciated this occasion to jog my brain on some ><> ! I still remember your invitation to come golf some more on code.golf by the way, I might find some time to do so soon ! :)

C (gcc), 43 33 bytes
f(x){x=~-x?f(x&1?3*x+1:x/2)+1:0;}

Try it online!

Ruby, 35 bytes
f=->n{n<2?0:1+f[n*3/(6-5*w=n%2)+w]}

Try it online!
How it works
Instead of getting the 2 values and choosing one, multiply by 3, divide by 1 if odd, or 6 if even, and then add n modulo 2.

-2 bytes

BitCycle -u, 90 bytes
 ~  ~!
?v C/v
v<   <
A\\ B^
>/\/C =v
  Cvv  <
  v~v/
  >   ^
  v =
>> >>^
\~~~
 ~v~^
^ + ~

Try it online! Or, watch it in action here.
Algorithm
The main loop starts with the current number \$n\$ in unary in the A collector. We divide the number by 2, splitting off two bits at a time; one of the halves, \$\lfloor \frac n 2 \rfloor\$, goes into the uppermost C collector; the other half goes into the middle C collector; and the remainder, \$n\text{ mod }2\$, goes into the bottom C collector.
Once the number is completely divided up in this way, the C collectors open.

The top C collector sends a 1 to the sink at the top right, adding 1 to the output, and sends all of its bits back into A.
If the bottom C collector is empty (i.e. \$n\text{ mod }2 = 0\$, i.e. \$n\$ was even), the first bit from the middle collector hits the bottommost switch = and activates it pointing right, which discards the bits. This leaves A with just the \$\lfloor\frac n 2\rfloor\$ bits it got from the top C collector: \$n\text{ even}\to n/2\$.
If the bottom C collector contains a 1 bit (i.e. \$n\text{ mod }2 = 1\$, i.e. \$n\$ was odd), a negated copy of it hits the bottommost switch and activates it pointing left. This sends the bits from the bottom and middle C collectors into the big collection of dupnegs ~ at the bottom, which makes five copies of its input and discards one bit. All the copies are then sent back into A: \$n\text{ odd}\to \lfloor\frac n 2\rfloor + 5\left( \lfloor\frac n 2\rfloor + 1\right) - 1 = 6\lfloor\frac n 2\rfloor + 3 + 1 = 3n + 1\$.

This whole process repeats until \$n=1\$, at which point the two halves are 0; this means the only C collector with data is the bottommost one that holds the remainder. The remainder bit is directed up to the uppermost switch =. Normally, this switch would have been activated by the bits from the middle C collector already, and the remainder bit would follow them into the 5-times circuitry. But since the middle C collector is empty, the remainder bit passes through the switch and continues northward off the playfield. Since there are no bits remaining on the playfield, the program halts and displays the number of steps taken.

x86 machine code, 15 bytes
xxd -g1:
00000000: 99 42 8d 4c 40 01 d1 e8 0f 42 c1 75 f4 4a c3     .B.L@....B.u.J.

Commented assembly (NASM syntax):
    [bits 32]
    global collatz
    ; input: eax, assumed positive and > 1
    ; output: edx
    ; clobbers: eax, ecx, edx
collatz:
    cdq                       ; count = 0 (abuses eax > 1)
.Lloop:
    inc    edx                ; increment count
    lea    ecx, [eax+2*eax+1] ; tmp = 3*n + 1
    shr    eax, 1             ; n = n / 2, sets flags
    cmovc  eax, ecx           ; swap with 3n+1 if it was originally odd (does not set flags)
    jnz    .Lloop             ; shr also sets ZF if the shr result was zero, end condition
    dec    edx                ; Correct the off by one
    ret                       ; return

Try it online! (converted to GAS Intel syntax and wrapped in C++)
Notes
The way this works is by using shr magic, allowing me to calculate n/2 and also test if n was originally odd (CF=1) or originally 1 (ZF=1).
Unfortunately, this results in an off by one since it will run when n == 1, but it is correctable via a simple dec.
Note that while this is larger than the other x86 solution, the other solution is a snippet, not a complete function, and it doesn't even count the steps, only calculating the sequence.
If that version were to count the steps, while it would be more efficient, it would be larger because the bsr complicates the bookkeeping, unless I can be proven otherwise.

bsf returns the count by itself, so you can just add that to the total count, but it's true that the other answer doesn't count at all.

Julia, 54 chars
f(n,i)=n==1 ? i : n%2==0 ? f(n/2,i+=1) : f(n*3+1,i+=1)

Try it online!
Julia, 45 chars
>(n,i=0)=n<2 ? i : n%2<1 ? n/2>i+1 : 3n+1>i+1

Try it online!
Thanks to the brilliant suggestion by MarcMush!

45 bytes

@MarcMush This is incredible! What exactly is n/2>i+1 for a construction (is > some special function?)?

I'm overloading the > function, and since it has lower precendence than +, you don't need parenthesis

This is brilliant!

if you haven't already, check out https://codegolf.stackexchange.com/questions/24407/tips-for-golfing-in-julia

No I haven't seen this before. Thank you I'll check it out!

you can avoid parenthesis altogether and save five more bytes Try it online!

@amelies no, because you're supposed to initialize the variable in the function, not ask the user to do it. This is more or less this forbidden loophole

@MarcMush I agree. This is indeed a forbidden loophole.

Pyth 23byte
J0WtQ=Q@,/Q2h*3QQ=JhJ;J

Welcome to Code Golf, and nice answer!

newLISP - 94 chars
Strangely similar to Valentin's Scheme answer... :) I'm let down here by verbosity of the language but there's a bitshift division which appears to work...
(let(f(fn(x)(cond((= x 1)0)((odd? x)(++(f(++(* 3 x)))))(1(++(f(>> x)))))))(f(int(read-line))))

TCL 8.5 (71 70 68) (67)
TCL has no real chance of ever winning, but it is a fun way to oil the machine:
proc c x {while \$x>1 {set x [expr $x%2?3*$x+1:$x/2];incr k};set k}

formatted for readability:
proc c x {
    while {$x>1} {
    set x [expr $x%2 ? 3*$x+1 : $x/2]
    incr k
    }
    set k
}

Edits: many suggestions (inspired) by sergiol. I guess the answer is more theirs than mine, by now :-)

is all the whitespace really neccessary?

@JanDvorak I think it is, in TCL.

@JanDvorak Yes, as far as I know. Say, trying 'while{$x>1}'  results in the error 'invalid command name "while{7>1}"' (executing 'tclsh collatz-conjecture.tcl 7'). That is, the interpreter substitutes $x, and then assumes the resulting string to be a command, and it is quite liberal to what may be a command name.

Didactic post to make me now that applying incr to an undefined variable interprets it as 0 and then does the increment!

You can shave one character off if you replace while {$x>1} by while \$x>1

@sergiol done, tks :-)

@RolazaroAzeveires: You are loosing to answers which implement it as a function. I purpose sthg like: proc c x {while \$x>1 {set x [expr $x%2?3*$x+1:$x/2];incr k};set k} — 67. demo: http://rextester.com/LLUS24241

@sergiol Right. I also note that set k could have been used in the "full program" version, which would bring it down to 68. I'll use both (somehow a function instead of a full program feels like cheating :-) as a function needs to be called from somewhere)

Game Maker Language, 63 61 60 bytes
Make script/function c with this code and compile with uninitialized variables as 0:
a=argument0while(a>1){i++if i mod 2a=a*3+1else a/=2}return i

Call it with c(any number) and it will return how many times it took to become 1.

Python (73):
Can probably be golfed a heck of a lot more.
i=0
while 1:
 i+=1;j=i;k=0
 while j!=1:j=(j/2,j*3+1)[j%2];k+=1
 print i,k

Haskell 73 Bytes 73 Chars
r n |even n=n`quot`2
    |otherwise=3*n+1
c=length.takeWhile(/=1).iterate r

otherwise in golf??? Use 1>0

You can save another 2 chars with takeWhile(>1) and \div``.

Fish (33 chars including whitespace, 26 without)
:2%?v:2,  >:1=?v
    >:3*1+^;nl~<

The whitespace is necessary for it to function, as ><> is a 2D language.
Example run:
$ python3 fish.py collatz.fish -v 176
18

Python 2, 59 57 55 54 bytes
i=0;n=input()
while~-n:n=[n/2,n*3+1][n%2];i+=1
print i

You can remove the indentation and newline for the while loop, while n>1:n=.... works the same.

@EᴀsᴛᴇʀʟʏIʀᴋ Thanks, I thought that didn't work when there are multiple statements inside.

It does work, as long as you don't have any other "indent required" statements such as another loop.  Semicolons work fine for plain statements though.

Can't you remove greater than 0, as it can only be 1 or 0?

@DestructibleWatermelon You're right, thanks.

Since n can't be 0, can you do while~-n: to save a byte?

@DestructibleWatermelon Yeah, that works, thanks. I don't use bitwise operators too much, didn't think of that.

Haskell, 43 Bytes
c 1=0
c x|odd x=1+c(3*x+1)|1<2=1+c(x`div`2)

Usage: c 7-> 16

What's "Haskell 2"?

@nyuszika7h: a typo

K, 24 bytes
#1_(1<){(x%2;1+3*x)x!2}\

With test cases:
  (#1_(1<){(x%2;1+3*x)x!2}\)'2 16 5 7
1 4 5 16

This uses a bit of a cute trick to avoid conditionals- (x%2;1+3*x) builds a list of the potential next term and then the parity calculated by x!2 indexes into that list. Otherwise it's a straightforward application of the "do while" form of \, given the tacit predicate (1<) (while greater than 1) as a stopping condition:
  (1<){(x%2;1+3*x)x!2}\5
5 16 8 4 2 1

The example output indicates that we need to drop the first (1_) of this sequence before taking the count (#). This is slightly shorter than taking the count and then subtracting one.

Befunge, 42 40 bytes
Surprisingly short to be an esolang! I thank @Sok for showing how to avoid one extra branching in his answer. Saved 2 bytes after a complete rewriting of the code.
0&>\1+\:2/\:3v
.$<v_v#%2\+1*<@
`!|>\>$:1

Original answer:
1&>:2%v>2v
^\+1*3_^ /
>+v  v`1:<
^1\#\_$.@

Shold be compatible with both Befunge 93 and Befunge 98. Interpretor available here.
There is no need for a trailing white space after @, so I count it as 42. However, 2D languages are often counted by their bounding box.

We count all answers by their length in bytes. If you don't need the trailing space, leave it off and save yourself a byte. Bounding box doesn't matter here.

Glad to have helped :o)

If you try to pop a value from the stack, and there aren't any values on the stack, a 0 is popped. Therefore, the stack is filled with an infinite amount of 0s for practical purposes. Because of this, you don't need the 0 at the beginning of your program, letting you shift over each line to save a byte. I can suggest an edit to show you what I mean, if you want.

Python 2, 38 37 bytes
f=lambda n:n<3or-~f([n/2,n*3+1][n%2])

Thanks to @user84207 for a suggestion that saved 1 byte!
Note that this returns True instead of 1.
Try it online!

you could save one byte by using n<1or instead of n>1and

@user84207 n<1or doesn't work (n is never less than 1) and n<2or would be off by one, but n<3or works just fine. Since 0 == False and 1 == True in Python, returning Booleans is allowed by default.

Clojure, 60 bytes
(fn c[n](if(= n 1)0(inc(c(if(even? n)(/ n 2)(+(* n 3)1))))))

Pretty standard. Recursive function that recurses when n isn't equal to one. Each iteration, one is added to the accumulator via inc.
While this uses unoptimized recursion, I'm currently testing to see when it fails. It's at 1711000000, and is still going. The highest number of steps I've seen so far is 1008, so I don't expect it to fail anytime soon.
Pregolfed:
(defn collatz-conj [n]
  (if (= n 1)
    0 ; Base case
    (inc ; Add one to step
      (collatz-conj ; Recurse
        (if (even? n) ; The rest should be be self-explanatory
          (/ n 2)
          (+ (* n 3) 1))))))

You can save 1 byte by using odd? instead of even?.
You can save another byte by replacing (inc(...)) with (+(...)1)

Alice, 26 bytes
/2:k@
.i#o3*hk
^d/.2%.j.t$

Try it online!
Explanation
This makes use of Alice's "jump and return" commands which allow you to implement subroutines. They're not at all separately scoped or otherwise encapsulated and nothing is stopping you from leaving the "subroutine", but if you want you can basically use them to jump to a different place in the code to do whatever you need and then continue where you left off. I'm using this to choose between two different "subroutines" depending on the parity of the current value to either halve it or triple and increment it.
To count the number of steps, we simply make a copy of the value at each step and check the stack depth at the end.
/     Reflect to SE. Switch to Ordinal.
i     Read the input as a string.
/     Reflect to E. Switch to Cardinal.
.     Duplicate the input.
2%    Take the current value modulo 2 to get its parity.
.     Duplicate it. So for even inputs we've got (0, 0) on top of the stack
      and for odd inputs we've got (1,1).
j     Use the top two values to jump to the specified point on the grid. That's
      either the top left corner, or the cell containing the i.
      Using j also pushes the original position of the IP (the cell containing j
      in this case) to a separate return address stack, so we can return here
      later.
      Note that the IP will move before executing the first command.

      Subroutine for even values:

  2:    Divide by 2.
  k     Pop an address from the return stack and jump back there (i.e. to the j).

      Subroutine for odd values:

  #     Skip the next command (the 'o' is there for a later part of the code).
  3*    Multiply by 3.
  h     Increment.
  k     Pop an address from the return stack and jump back there (i.e. to the j).

      Either way, we continue after the j:

.     Duplicate the new value.
t     Decrement it, to get a 0 if we've reached 1.
$     Skip the next value if the result was 0.

      This part is run if the current value wasn't 1 yet:

  ^     Send the IP north.
  .     Duplicate the current value to increase the stack depth.
  /     Reflect to SW. Switch to Ordinal.
        Immediately reflect off the left boundary and move SE.
  i     Try to read more input, but this just pushes an empty string.
        However, the next command will be the duplication . which tries to
        duplicate an integer, so this empty string is immediately discarded.
        After that we start the next iteration of the loop.

     This part is run once the value reaches 1:

  d     Push the stack depth.
  /     Reflect to SE. Switch to Ordinal.
        Immediately reflect off the bottom boundary and move NE.
  o     Implicitly convert the stack depth to a string and print it.
  @     Terminate the program.

Aceto, 33 bytes
&)
(I2/(I)&
+3_!
1*2%
i@d|(
rd1=p

Explanation:
Read an integer:
i
r

Set a catch point, duplicate the number and check if it's 1, if so, we mirror horizontally (meaning we end up on the ( next to the |):
 @ |
 d1=

Duplicate the value again, check if it's divisible by 2, if so, we mirror vertically (ending up on the 2 above):
  _!
  2%

Otherwise, multiply by 3, add 1, go one stack to the left, increment the number there (initially zero), go back to the original stack, and raise (jumping back to the catch point):
&)
(I
+3
1*

If it was divisible, we divide the number by two, and again increment the stack to the left and jump to the catch point:
  2/(I)&

When the number is 1 after jumping to the catch point, we go to the left stack and print that number (and exit):
    (
    p

Acc!!, 127 75 bytes
Count u while N/49 {
_+1
}
Count i while _-1 {
_/2+_%2*(5*_/2+2)
Write 49
}

The program takes input and produces output in unary. Try it online!
(Here's a decimal I/O version in 209 bytes.)
With comments
# Read input in unary
Count u while N/49 {   # Increment u from 0 while input character is >= "1"
  _+1                  # Add one to accumulator
}

# Main loop
Count i while _-1 {    # Increment i from 0 while accumulator is not equal to 1
  _/2+_%2*(5*_/2+2)    # Apply one step of Collatz function to accumulator
  Write 49             # Write "1" to output
}

The expression _/2+_%2*(5*_/2+2) boils down to
_/2,               if _%2 is 0
_/2 + (5*_)/2 + 2, if _%2 is 1

This is integer division, so the latter case comes out to
_/2 + 2*_ + _/2 + 2
 = 2*_ + (_/2)*2 + 2
 = 2*_ + _ + 1
 = 3*_ + 1

Emacs/Common Lisp, 61 bytes
(defun f(n)(if(= 1 n)0(1+(f(if(oddp n)(1+(* 3 n))(/ n 2))))))

alternatively:
(defun f(n)(if(= 1 n)0(1+(f(if(oddp n)(+ n n n 1)(/ n 2))))))

Befunge-93, 29 bytes
&<\+1\/2+*%2:+2*5:_$#-.#1@#:$

Try it online!
A nice and concise one-liner. This uses the formula (n+(n*5+2)*(n*5%2))/2 to calculate the next number in the series.

Emojicode, 157 bytes
➡ac 0▶a 1a 2 0a➗a 2a➕✖a 3 1c➕c 1c 10

Try it online!
Explanation:

➡
a       input integer variable 'a'
c 0          counter variable
▶a 1       loop while number isn’t 1
a 2 0      if number is even
a➗a 2        divide number by 2

       else
a➕✖a 3 1    multiply by 3 and add 1

c➕c 1      increment counter

c 10    return final count as string

  16

MATL, 21 16 bytes
Saved 5 bytes thanks to Luis Mendo! I didn't know while had a finally statement that could be used to get the iteration index. Keeping track of the number of iterations took a lot of bytes in my original submission.
`to?3*Q}2/]tq}x@

Try it online!
Explanation:
`t                % grab input implicitly and duplicate it.
                  % while ...
 o?                % the parity is `1` (i.e. the number is odd
   3*Q              % multiply it by 3 and increment it
  }                % else
   2/               % divide it by 2
  ]                % end if
 tq               % Duplicate the current value and decrement it
}                 % Continue loop if this value is not zero (i.e. the current value is >1
x                 % Else, delete the current value (the 0)
@                 % And output the "while index" (i.e. the number of iterations)

MathGolf, 7 bytes
kÅ■┐▲î

Don't get fooled, there's a non-breaking space at the end of the program.
Try it online!
Explanation
k        Read input as integer
 Å       Start a block of length 2
  ■      Map TOS to the next item in the collatz sequence
   ┐     Push TOS-1 without popping
    ▲    Do block while TOS is true
     î   Push the length of the last loop
         Discard everything but top of stack

MathGolf, 14 bytes (no built-ins, provided by JoKing)
{_¥¿É3*)½┐}▲;î

Explanation
{               Start block of arbitrary length
 _              Duplicate TOS
  ¥             Modulo 2
   ¿            If-else (works with TOS which is 0 or 1 based on evenness)
    É3*)        If true, multiply TOS by 3 and increment
        ½       Otherwise halve TOS
         ┐      Push TOS-1 (making the loop end when TOS == 1)
          }▲    End block, making it a do-while-true with pop
            ;   Discard TOS
             î  Print the loop counter of the previous loop (1-based)

Ideally, this solution could become 13 bytes, since it's not neccessary to have the ending of the block be explicit when the loop type instruction comes right after. I'll see when I get around to coding implicit block ending when loop type is present.
Try it online!

This is 12 bytes if you don't use the collatz operator

Nice solution! I'll have to analyze a bit before I understand it completely. I wrote this solution when the language was still really new, there are a bunch of new features now

@JoKing I've looked your solution over, and I might have to clarify the documentation, ∙ (documented as "triplicate TOS") does not push TOS*3, but instead pushes TOS 3 times. Your solution gives the correct input for powers of 2, but fails for e.g. input 7.

Lol, my bad. In that case, it would be 14 bytes

Pushy, 24 bytes
Zvt$h2C3*h}2/}2%zFhFt;F#

Try it online!

05AB1E, 16 15 bytes
-1 byte thanks to Kevin Cruijssen
[Éi3*>ë2÷}¼Ð#]¾

Try it online!
Explanation
                  # Implicit input: integer n
[              ]  # Infinite loop
   i       }      # if:
  É               # n is odd
    3*>           # compute 3n+1
       ë          # else:
         2÷       # compute n//2
            ¼     # increment counter variable
             Ð    # Triplicate
              #   # Break loop if n = 1
                ¾ # output counter variable

wait. why does halve not work? floating point errors, i guess?

yup, it turns integers into floats and I dont see a way to implicitly turn it into an integer again after halving

You can save a byte removing the first D and changing the second D to Ð (in the first iteration it will implicitly use the input twice). (And you might want to change n/2 to n//2 or n integer-divided by 2 in your explanation to make it clear you're integer-dividing.)

Thanks @KevinCruijssen! I am still bad at taking advantage of implicit input :-)

14 bytes

The 1.0 not being truthy in the new version has been fixed, so 2÷ can be ;. In addition, here is 12 bytes in the legacy version of 05AB1E (based on the 14-byter of @Zylviij).

Pip, 23 21 19 bytes
a>1&URE[HVa3*a+1]@a

Try It Online! Note that this is a recursive solution; moderately large numbers of iterations will cause a recursion error.
Explanation
a>1&URE[HVa3*a+1]@a
a>1                  Is the argument greater than 1?
   &                 If not, return 0; if so, return
    U                1 plus
     RE              Recursive call to the main function with this argument:
       [        ]      Construct a list containing two elements:
        HVa              Half of the argument
           3*a+1         3 times the argument plus 1
                 @     Select the element at (modular) index of
                  a    The argument

A non-recursive solution in 21 bytes:
Wa>1&Uia:%a?3*a+1HVai
                       i is 0; a is first command-line argument (implicit)
Wa>1                   While a>1
    &Ui                (and if it is, increment i):
       a:               Set a to:
         %a?             If a mod 2 is nonzero (a is odd),
            3*a+1         3*a+1;
                 HVa      else, halve a
                    i  Autoprint i, the iteration count

The original 23-byte solution in Pip Classic is similar: Try it online!

Forth (gforth), 71 bytes
: f begin dup 2 mod if 3 * 1+ else 2/ then dup dup 1 = until depth 1- ;

Try it online!
Uses an until loop, and computes stack depth -1.
Forth (gforth), 76 bytes
: f dup dup 1 = if 0 else 2 mod if 3 * 1+ else 2/ then dup recurse 1+ then ;

Try it online!
A recursive function.

Racket, 51 characters, 28 brackets
(define(a n)(do([i 0(+ i 1)][x n(if(even? x)(/ x 2)(+ 1(* 3 x)))])((= 1 x) i)))

Praise the do. Love the do.

Welcome to Code Golf! Nice first answer.

Julia 1.0, 29 bytes
!n=n>1&&1+![n÷2,3n+1][n%2+1]

Try it online!
Based on Dennis' answer

LOLCODE, 217 bytes
HAI 1
I HAS A N
GIMMEH N
I HAS A C
IM IN YR L UPPIN YR D WILE DIFFRINT N 1
BOTH SAEM MOD OF N 2 0,O RLY?
YA RLY,N R QUOSHUNT OF N 2
NO WAI,N R SUM OF PRODUKT OF N 3 1
OIC
C R D
IM OUTTA YR L
VISIBLE SUM OF C 1
KTHXBYE

Try it online!

Husk, 12 11 bytes
€2¡?o→*3½%2

Try it online!
Explanation
€2¡?o→*3½%2
  ¡          Infinitely iterate the following function:
   ?           If
         %2    the argument mod 2 is 1:
    o            Compose:
     →             Increment
      *3           Times three
        ½      Else, halve
€2           Index (1-based) of first occurrence of 2 in that infinite list

Java (136)
public class C {public static void main(String[] a) {int i=27,c=0;while(i!=1;{c++;if(i%2==0)i/=2;else i=3*i+1;}System.out.println(c);}}

Just change the value of i to the input. For 27, it prints 111 to the console.
Whitespace view:
public class C {
    public static void main(String[] a) {
        int i=27,c=0;
        while(i!=1) {
            c++;
            if(i%2==0)
                i/=2;
            else
                i=3*i+1;
        }
        System.out.println(c);
    }
}

I know it isn't the shortest, but I figured I'd give it a whirl. Any suggestions would be appreciated. ;)
I have to say I'm a little envious of all those who know the short languages. I'd love to see this done in Brainf**k.

Wish granted

This Programming Language, 59
v>v>_1=?v_2%?v2/  v
}0"     >~"i;>3*1+v
>^>^          "+1"<

Not the shortest, but an interesting program nonetheless.

If this is anything like ><>, that's a lot of whitespace that could be golfed out...

I wrote this program with a headache and I'm not really in the mood to golf it right now.

Pyth 27 23 22 chars
W>Q1=hZ=Q?h*Q3%Q2/Q2)Z

online
Pyth is much newer than the challenge and therefore won't count as a winning candidate

Btw. W>Q1 is the same thing as WtQ

I didn't even look at the date ;) And thanks.

If your interested in a 18 bytes solution: fq1=Q?h*Q3%Q2/Q2 1 gives 18 bytes. And I'm sure you can golf this even further.

The usage of f...1 not really documented (at least not good). It basically means: "find the first number >= 1, that satisfies ..."

That's good to know, tried to find that on the docs but no luck

Oracle SQL 11.2, 122 bytes
WITH v(n,i)AS(SELECT:1,0 FROM DUAL UNION ALL SELECT DECODE(MOD(n,2),0,n/2,n*3+1),i+1 FROM v WHERE n>1)SELECT MAX(i)FROM v;

Un-golfed :
WITH v(n,i)AS   -- Recursive view, n=>current value, i=>iterations count
(
  SELECT :1,0 FROM DUAL -- Initialize with parameter and 0 iteration count
  UNION ALL
  SELECT DECODE(MOD(n,2),0,n/2,n*3+1),i+1 -- Compute the next value
  FROM   v WHERE n>1 -- End when it reaches 1
)
SELECT MAX(i)FROM v -- Return only the last iteration count

Mathcad, 36 "bytes"

From user perspective, Mathcad is effectively a 2D whiteboard, with expressions evaluated from left-to-right,top-to-bottom. Mathcad does not support a conventional "text" input, but instead makes use of a combination of text and special keys / toolbar / menu items to insert an expression, text, plot or component.   For example, type ":" to enter the definition operator (shown on screen as ":=") or "ctl-]" to enter the while loop operator (inclusive of placeholders for the controlling condition and one body expression).  What you see in the image above is exactly what appears on the user interface and as "typed" in.
For golfing purposes, the "byte" count is the equivalent number of keyboard operations required to enter an expression.

Keyboard operations required to enter an expression please?

Answer Part 1: Tricky. Becomes somewhat of a habit after a short time and I have to look at what I'm doing to answer this one ... ":" to enter the definition operator (:=), "]" for a programming line (black vertical bar after the :=), "ctl-#" for the while loop operator (see text), "3n" for implicit multiplication of n by 3, "shft-[" for local definition operator, "ctl-/" for in-line division operator, single-quote for balanced parentheses (context dependent).  After a while, a user develops their own method of keyboard and mouse editing, which means the entry sequence can be different.

Answer Part 2: Download Mathcad Express (http://www.ptc.com/engineering-math-software/mathcad/free-download - cutdown version of Mathcad Prime 3.1) and then Mathcad 15 (http://www.ptc.com/engineering-math-software/mathcad/free-trial).  This will allow you to play with them (M15 for 30 days, at least); Mathcad Express will give you full Prime 3.1 functionality for 30 days (including programming and symbolics).

QBIC, 34 33 bytes
:{~-a|_Xb\b=b+1~a%2|a=a*3+1\a=a/2

Pretty straightforward:
:           Name the Command Line Parameter 'a'
{           Start an infinite loop
~-a|_Xb     If 'a' = 1 (or -a = -1, QB's TRUE value), quit printing 'b'
\           ELSE (a > 1)
b=b+1       Increment step counter
~a%2        In QBasic, 8 mod 2 yields 0, and 0 is considered false
|a=a*3+1    Collatz Odd branch
\a=a/2      Collatz Even branch

Befunge 93, 37 bytes
Try it Online!
&>:1-|
\@#-1<+2_.#
v#%2:<+1*3:_
<v/2:

Explanation:
&         Take integer input
 >:1-|    If the top of the stack is 1, go to the 2nd line.
          Else, go the third.

----------------------------------------------

\  -1<+2_      The top of the stack is 1, which becomes the counter for
               the stack size. If the second-to-the-top of the stack is
               non-zero, consume that value and increment the counter by 1.

 @       .     If the second-to-the-top of the stack is 0, i.e. there are
               no elements besides the counter, output the counter and
               terminate the program.

----------------------------------------------

v#%2:<     _    The top of the stack is non-zero. Check if the top of
                the stack is divisible by 2, and execute 1 of the
                following accordingly:

      +1*3:     The top of the stack (a) is odd, so push 3a + 1,
                and check the top mod 2 again.

<v/2:           The top of the stack (a) is even, so push a / 2,
                and check if the top is 1 again.

Like other programs, this pushes each iteration onto the stack until the top is 1, and outputs the stack size - 1.
I was able to make this program shorter by not testing if the top was 1, if the previous iteration was odd. Also, in counting the stack size, I used the fact that the top of the stack will always be 1.

Clojure, 77 bytes
#(loop[x % a 0](if(= x 1)a(recur(if(=(mod x 2)0)(/ x 2)(+(* x 3)1))(inc a))))

Defines an anonymous function. Usage is like so:
(#(...) {num})

Ungolfed:
(defn collatz [n]
  (loop [x n
         a 0]
    (if (= x 1) a
      (recur (if (= (mod x 2) 0) (/ x 2) (+ (* x 3) 1)) (inc a)))))

C, 38 bytes
g(v){return v^1?1+g(v&1?v*3+1:v/2):0;}

Casio-Basic, 83 72 bytes
71 bytes for code, +1 for n as parameter.
0⇒z
While n≠1
piecewise(mod(n,2),3n+1,n/2)⇒n
z+1⇒z
WhileEnd
Print z

PARI/GP, 38 bytes
a(n)=if(n==1,0,a(if(n%2,3*n+1,n/2))+1)

Try it online!
Equivalent to this readable C code:
int b(n)
{
    if (n % 2)
        return 3 * n + 1;
    else
        return n / 2;
}

int a(n)
{
    if (n == 1)
        return 0;
    else
        return a(b(n)) + 1;
}

tinylisp, 68 67 bytes
(load library
(d f(q((n)(i(e n 1)0(inc(f(i(odd? n)(a(* 3 n)1)(/ n 2

Try it online!
This is the same recursive solution as, e.g., Carcigenicate's Clojure answer. Because tinylisp has only addition and subtraction built in, I load the standard library to get odd?, /, *, and inc. Other library functions would make the code longer; for instance, I'm defining the function manually with (q((n)(...))) rather than using (lambda(n)(...)). Here's how it would look ungolfed and indented:
(load library)
(def collatz
  (lambda (n)
    (if (equal? n 1)
      0
      (inc
        (collatz
          (if (odd? n)
            (add2 (* 3 n) 1)
            (/ n 2)))))))

Here's a 101-byte solution that doesn't use the library. The E function returns n/2 if n is even and the empty list (falsey) if n is odd, so it can be used both to test evenness and to divide by 2.*
(d E(q((n _)(i(l n 2)(i n()_)(E(s n 2)(a _ 1
(d f(q((n)(i(e n 1)0(a 1(f(i(E n 0)(E n 0)(a(a(a n n)n)1

* Only works for strictly positive integers, but that's exactly what we're dealing with in this challenge.

Attache, 11 bytes
CollatzSize

Try it online!
Not much to say...

Wumpus, 22 bytes
I]=2:~3*)=&~~!0~.
l(O@

Try it online!
Explanation
The first line is the main loop which iterates the Collatz function until we get 1. We keep track of the number of steps by growing the stack by one element on each iteration.
I   Read a decimal integer N from STDIN. At EOF (i.e. on subsequent
    iterations) this pushes 0 instead.
]   Rotate the stack right. On the first iteration, this does nothing, but
    afterwards this moves the 0 to the bottom of the stack.
=   Duplicate N.
2:  Compute N/2.
~   Swap with the other copy of N.
3*) Compute 3N+1.
=   Duplicate.
&~  3N+1 times: swap N/2 and 3N+1. If N is odd, 3N+1 is even and vice versa.
    We end up with the value that we want on top and the incorrect one
    underneath.
~   Swap them once more.
!   Logical NOT. 3N+1 is always positive and N/2 gives 0 iff N = 1 (in which
    case N/2 will also be on top of the stack). So this essentially gives us
    1 iff N = 1 (and 0 otherwise). Call this value y.
0~. Jump to (0, y), i.e. to the beginning of the second line once we reach N = 1
    and to the beginning of the first line otherwise.

Once we reach 1:
l   Push the stack depth. The stack holds one zero for each iteration as well
    as the final result. But note that we won't terminate until the iteration
    that process 1 itself (because we check the condition at the end of
    the loop, but based on its initial N). So the stack depth is one
    greater than the number of steps to reach 1.
(   Decrement.
O   Print as decimal integer.
@   Terminate the program.

I've got an alternative 22 byte solution, but unfortunately I haven't found anything shorter yet:
I]3*)=2%5*):=(!0~.
lO@

Japt, 18 15 bytes
É©Òß[U*3ÄUz]gUv

Try it

Java (OpenJDK 8), 54 bytes
a->{int c=0;for(;a!=1;c++)a=a%2>0?a*3+1:a/2;return c;}

Try it online!
This answer is a little to simple to justify an explanation, it’s just a while loop and a ternary expression.

PHP, 80 73 Bytes
Tried a recursive function Try it here! (80 Bytes)
Try it online (73 Bytes)
Code (recursive function)
function f($n,$c=0){echo($n!=1)?(($n%2)?f($n*3+1,$c+1):f($n/2,$c+1)):$c;}

Output
16 -> 4
2 -> 1
5 -> 5
7 -> 16

Explanation
function f($n,$c=0){ //$c counts the iterations, $n the input
echo($n!=1)?
(($n%2)?
    f($n*3+1,$c+1): //$n is odd
    f($n/2,$c+1))   //$n is even
:$c;                 //echo $c (counter) when n ==1
}

No, the test cases aren't part of the byte count. Your submission looks fine as it is.

Octave, 65 bytes
@(x)eval 'k=0;do++k;if mod(x,2)x=3*x+1;else x/=2;end,until x<2,k'

Try it online!
It's time we have an Octave answer here. It's a straight forward implementation of the algorithm, but there are several small golfs.
Using do ... until instead of while ... end saves some bytes. Instead of having while x>1,k++;...end, we could have do++k;...until x<2, saving two bytes. Using eval in an anonymous function saves a few bytes, compared to having input('').
Also, skipping the parentheses in the eval call saves some bytes.

Ruby, 48 bytes
(f=->n{n>1&&1+f[n%2<1?n/2:3*n+1]||0})[gets.to_i]

Same as other Ruby, but using n%2?a:b syntax instead of [a,b][n%2]. Saves one char.

You mention that you save one byte off of the other Ruby answer yet your answer is 13 bytes longer because of (...)[gets.to_i].  Even if I remove that (which doesn't break your answer) you still have the same length as the other answer.  This is ok, I just thought maybe you might have made a mistake.

Python 2, 48 bytes
f=lambda n,s=0:s*(n<2)or f((n/2,3*n+1)[n%2],s+1)

Try it online!
Aaah, recursion.
# s*0 or s*1.
s*(n<2)

# while n>1, this will evaluate to 0 or f(n,s+1).
# Since positive integers are Truthy, this will return f().
# when n<2, this will return s without evaluating f().
s*(n<2)or f(...)

JavaScript, 35 bytes
f=(n,c)=>n<2?c:f(n%2?n*3+1:n/2,-~c)

Try it online!

Keg -rR, 23 bytes (SBCS)
I really need to remember those new instructions.
0&{:1>|:2%[3*⑨|½]⑹

Try it online!

-5 bytes with -rR and new register commands

Wren, 68 bytes
Fn.new{|n|
var c=0
while(n>1){
n=n%2==0?n/2:n*3+1
c=c+1
}
return c
}

Try it online!
Explanation
Fn.new{|n| // New anonymous function with param n
var c=0    // Declare a variable c as 0
while(n>1){ // While n is larger than 1:
n=n%2==0?          // If n is divisible by 2:
         n/2:      // Halve n
             n*3+1 // Otherwise, triple n & increment.
c=c+1              // Increment the counter
}                  // This is here due to Wrens bad brace-handling system
return c           // Return the value of the counter
}

Kotlin, 63 bytes
{var n=it
var c=0
while(n>1){n=if(n%2==0)n/2 else n*3+1
c++}
c}

Try it online!

MAWP, 36 bytes
@[!!2P2WA{%3W1M}<%2P>1A{1M}/1M\]%1A:

Works as per the basic rules. Increments existing 1 in stack for each step.
Prints out n-1.
Try it!

Rust, 62 bytes
fn c(x:u8)->u8{if x==1{0}else{c(if x%2==0{x/2}else{x*3+1})+1}}

This recursively determines the total. For 2 extra bytes u8 can be changed to u64 to support all 64-bit integers instead of just 8-bit ones.

Welcome to the site, and nice first answer! Be sure to check out our Tips for golfing in Rust page for ways you can golf your program

Lua, 75 bytes
function C(x)z=0 while x>1 do x=({x//2,3*x+1})[x%2+1]z=z+1 end return z end

Try it online!

Python - 101 bytes
n=int(input())
m=0
while n>1:
  if n%2==0:
    n=n/2
    m+=1
  else:
    n=3*n+1
    m+=1
if n==1:
  print(m)

This assumes n is inputted to STDIN as an integer. If it is not explicitly that, a type check is most certainly possible, but would cost a few bytes, i.e.
if type(n) != int:
 print(N/A)

(edit 1: input is so expensive)

71 bytes

Burlesque, 26 bytes
1{J2dv{2./}{3.*+.}IE}C~1Fi

Try it online!
1          #Needed for C~
{
 J         #Duplicate
 2dv       #Even
 {2./}     #Halve
 {3.*+.}   #3n+1
 IE        #If even, else
}
C~         #Continue indefinitely
1Fi        #Find index of 1

Python 3, 64 bytes
def f(n,a=0):
    while n>0:n=[n//2,n*3+1][n%2];a+=1
    yield a

Try it online!

INPUT A
Y:
IF A MOD 2=0 THEN
  B=A/2
  PRINT B
  A=B
  ELSE
  B=A*3+1
  PRINT B
  A=B
  END IF
IF A>1 THEN
  GOTO Y
  ELSE
  END IF

Welcome to Code Golf! Could you edit in the language used, along with the length (in bytes) of your code, as this is a [code-golf] challenge? I've edited your answer slightly to format the code properly

C (gcc) 38, 37 bytes (thanks to @UnrelatedString)
c(x){return~-x?-~c(x%2?3*x+1:x/2):0;}

First recursive solution that came to mind. Fairly simple.  Explanation (ungolfed):
int c() {
 return~-x? //If x!=1
       -~c(x%2?3*x+1:x/2) // Compute the next term and recurse on that term. Add 1.
       :
       0; //Base case
}

-1

Nice! Thanks. I forgot to take advantage of two's complement!

Vyxal, 17 12 11 bytes
∷[T›|½)İ2ḟ⇧

Try it Online!
-5 bytes thanks to lyxal
Removed flag thanks to emanresu A.

Try it Online! for 12 bytes

Flagless 11 (husk port)

@emanresuA Alternative: ‡₍½‡T›iİ2ḟ⇧

Try it Online! for 10 bytes/7.875 bytes. Uses newer functionality that didn't exist back when this answer was made.

Desmos, 63 bytes
i->.5si(5k+1)+sk-s+1,o->o+s
i=\ans_0
o=0
k=mod(i,2)
s=sign(i-1)

Output is the value of o after the code finishes running.
Have fun trying to figure out how this works! (It's really not as complicated as it seems)
Try It On Desmos!
Try It On Desmos! - Prettified

Ruby, 60 bytes
n,i=gets.to_i,0;while n>1 do n=n%2==0?n/2:n*3+1;i+=1 end;p i
Pretty readable and easy to understand compared to the previous Ruby submission.
Attempt This Online!

56 bytes

Factor + project-euler.014, 22 bytes
[ collatz length 1 - ]

Try it online!

Haskell (54 bytes)
c n a|n<2=a|odd n=c(3*n+1)(a+1)|even n=c(div n 2)(a+1)

This function takes two arguments, the value n and an accumulator a. The type signature is: c :: Int -> Int -> Int.
In expanded form:
collatz n acc
  | n < 2  = acc
  | odd n  = collatz (3 * n + 1) (acc + 1)
  | even n = collatz (div n 2) (acc + 1)

I forget where this is spelled out on Meta, but you can't expect extra input. Fortunately, it can be golfed more than enough to compensate (and without abandoning the accumulator, which would result in nimi's existing solution).

brev, 71 bytes
(rec(f x)(cond((= x 1)0)((odd? x)(+(f(+(* 3 x)1))1))(1(+(f(/ x 2))1))))

Fig, \$15\log_{256}(96)\approx\$ 12.347 bytes
#?{x}oX?Ox}*3xH

Try it online!
This challenge does not lend itself well to Fig's implicit inputs...
#?{x}oX?Ox}*3xH
  {x            # Decrement the input
#?              # If ^ is false, return ^, else return...
     oX         # Call this function with the following argument:
       ?Ox      # If odd
           *3x  # Multiply by 3
          }     # Add 1
                # Else
              H # Halve
    }           # After calling this function, increment the result

Thunno 2, 17 bytes
(1Q;Dɗ?3×⁺:½;ẋ)x⁻

Attempt This Online!
Only works in Thunno \$\le 2.1.9\$. In versions \$\ge 2.1.10\$, ẋ can be replaced with ẋ⁺.
Explanation
(1Q;Dɗ?3×⁺:½;ẋ)x⁻  # implicit input; x is initialised to 1
(1Q;          )    # while TOS != 1:
    D              #   duplicate
     ɗ?            #   if TOS is odd:
       3×⁺         #     triple and increment
          :        #   else:
           ½       #     halve
            ;ẋ     #   increment x
               x⁻  # push x and decrement
                   # implicit output

Nekomata, 10 bytes
ˡ{1>ᵉ½3*→I

Attempt This Online!
ˡ{1>ᵉ½3*→I
ˡ{          Repeat the following function until it fails, and count the number of steps:
  1>            Check if greater than 1
    ᵉ           Parallelly apply the following two functions:
     ½              Check if it is even, and divide by 2
      3*→           Multiply by 3 and add 1
         I      Choose the first result that does not fail

Uiua, 23 bytes
⧻⍢(⊂0⟨÷2|+1×3⟩◿2.|¬∊2)¤

Explain:
⧻                       # length of list
 ⍢(              |   )  # do while
   ⊂0                   # prepend 0 to the list
     ⟨÷2|+1×3⟩◿2.       # apply collatz the the whole list
                  ¬∊2   # while the list doesn't contain 2
                      ¤ # arg as list

Axiom, 74 bytes
g(a)==(c:=0;repeat(a<=1=>break;c:=c+1;a rem 2=0=>(a:=a quo 2);a:=3*a+1);c)

ungolfed
gg(a)==
   c:=0
   repeat
      a<=1     =>break
      c:=c+1
      a rem 2=0=>(a:=a quo 2)
      a:=3*a+1
   c

results
(3) -> [i,g(i)] for i in [2,16,5,7,1232456,123245677777777777777777777777777]
   Compiling function g with type PositiveInteger -> NonNegativeInteger
   (3)
   [[2,1], [16,4], [5,5], [7,16], [1232456,191],
    [123245677777777777777777777777777,572]]
                                      Type: Tuple List NonNegativeInteger

R, 57 55 bytes
x=scan();n=0;while(x-1){x='if'(x%%2,3*x+1,x/2);n=n+1};n

Not much to say, uses a nice statement within the while loop, which should become 0 -> False only when x=1, similar to the check whether x is odd or even. This also uses the implicit conversion of 0->False and nonzero -> True.
Saved 2 bytes thanks to a trick by @Billywob used in this answer.

Abusing a built-in (F) saves 4 bytes - the other change is just a different way of doing the if, not golfier.

C#, 71 bytes
Assuming output is required as opposed to just a return
n=>{int i=0;while(n>1){n=n%2<1?n/2:n*3+1;i++;}System.Console.Write(i);}

Java (OpenJDK), 53 bytes
n->{int i=0;for(;n>1;i++)n=n%2<1?n/2:n*3+1;return i;}

Try it online!

Java 8, 53 bytes
i->{for(;i>1;)System.out.print(i=i&1>0?i=3*i+1:i/2);}

Another solution(Java 9)
i->IntStream.iterate(i,j->j&1>0?j*3+1:j/2).takeWhile(n->true);

SmileBASIC, 54 bytes
INPUT N
WHILE N-1D=1AND N
C=C+1N=N*3*D+D+N/2*!D
WEND?C

TI-Basic, 47 bytes
Prompt A
0→B
While A-1
Aremainder(A+1,2_/2+(3A+1)remainder(A,2→A
B+1→B
End
B

S.I.L.O.S, 76 bytes
readIO
lbla
I=1-(i%2)
if I x
i=i*6+2
lblx
i/2
x+1
I=1-i
I|
if I a
printInt x

Try it online!
Somewhat naively implements the spec. It avoids a couple extra lines at the cost of performance by multiplying i by 6 and adding 2, then dividing by two when the number is odd.

Emojicode, 139 bytes
➡ai 0❎1a1a 2a➕1✖3aa➗a 2i➕1ii

Try it online!

Clean, 82 bytes
import StdEnv
?n=snd(until(\(e,_)=e<2)(\(e,i)=(if(isOdd e)(3*e+1)(e/2),i+1))(n,0))

Try it online!

Stax, 12 bytesCP437
ÄFl,rBoU¡£&╦

14 bytes when unpacked,
1{h_3*^\_@gt%v

Run and debug online!
Adaptation of https://github.com/tomtheisen/stax/blob/master/testspecs/golf/CollatzTest.staxtest .

SNOBOL4 (CSNOBOL4), 96 bytes
	N =INPUT
T	X =X + 1
	N =GT(REMDR(N,2)) 3 * N + 1	:S(O)
	N =N / 2
O	OUTPUT =EQ(N,1) X	:F(T)
END

Try it online!

Add++, 50 bytes
D,f,@,dd2/i@3*1+$2%D
+?
-1
W,+1,$f>x,},+1,},-1
}
O

Try it online!
-5 bytes thanks to rubber duck golfing!
How it works
D,f,@,		; Define a function 'f' that takes one argument
		; Example argument:	[10]
	dd	; Triplicate;	STACK = [10 10 10]
	2/i	; Halve;	STACK = [10 10 5]
	@	; Reverse;	STACK = [5 10 10]
	3*1+	; (n*3)+1;	STACK = [5 10 31]
	$	; Swap;		STACK = [5 31 10]
	2%	; Parity;	STACK = [5 31 0]
	D	; Select;	STACK = [5]

+?		; Take input; 	x = 10;	y = 0;
-1		; Decrement;	x = 9;	y = 0;

W,		; While x != 0:
	+1,	;  Increment;	x = 10;	y = 0;
	$f>x,	;  Call 'f';	x = 5;	y = 0;
	},+1,	;  Increment y;	x = 5;	y = 1;
	},-1	;  Decrement x;	x = 4;	y = 1;

}		; Swap to y;	x = 0;	y = 6;
O		; Output y;

dc, 30 28 bytes
?[d5*2+d2%*+2/d1<f1+]dsfx1-p

This uses the formula from Jo King's answer, slightly adapted so we dup after adding 2.
Explanation
?                             # read input
 [            d1<f  ]dsfx     # repeat until we reach 1
  d5*2+d2%*+2/                # n → (n + (5n+2)%2 * (5n+2)) / 2
                  1+          # count iterations
                         1-p  # decrement and print result

Previous answer: 30 bytes
?[6*4+]sm[d2~1=md1!=f]dsfxz1-p

We keep all the intermediate results on the stack, then count the size of the stack.  We save bytes by always doing the division by two, but if the remainder is 1, then we multiply by 6 and add 4 (3 for the remainders and 1 for the Collatz constant).  The final stack count contains all the numbers we've seen; the number of operations is one less than that.
Explanation
?                               # input

[6*4+]sm                        # helper function

[d2~1=md1!=f]dsfx               # recursion

z1-p                            # print result

Julia 0.6, 43 bytes
c(n,l=0)=n<2?l:n%2>0?c(3n+1,l+1):c(n/2,l+1)

Try it online!

Ahead, 38 bytes
Il&+1t~j+1*3\~/2<~<
>:1)k~tO@~:k\:  nl

Try it online!

Ruby, 77 72 bytes
b=0;a=gets.to_i;loop{if a==1;p b;exit;end;a.odd?? (a*=3;a+=1):a/=2;b+=1}

Definitely not the shortest, but not the most unreadable or hard to follow either. Try it online!
a.odd?? (a*=3;a+=1): uses the ternary operator, which is a short form of if/then/else. It looks like boolean ? instruction : instruction, with the first instruction being if the boolean is true, and the second being if it isn't. Therefore trailing question mark and colon.
*= and /= are the multiplication and division versions of += in Ruby.
Ungolfed version:
counter = 0
input = gets.to_i
loop do
  if input = 1
    print counter
    exit
  end
  if input.odd?
    input *= 3
    input += 1
  else
    input /= 2
  end
  counter += 1
end

Haskell, 47 bytes
c n|n==1=0|even n=1+c(div n 2)|odd n=1+c(3*n-1)

Ungolfed:
c n
    | n == 1 = 0
    | even n = 1 + c (div n 2)
    | odd n  = 1 + c (3*n-1)

A recursive function that returns the number of times it's been run, excluding when n==1.

HBL, 16 15 bytes
?(%.)(+(*.<))(/.2
?(-.)(-+?().

Try it!
Explanation
Helper function:
?(%.)(+(*.<))(/.2
?                  If
   .               the argument
 (% )              is odd:
     (+     )       Increment
       (*  )        the product of
         .          the argument
          <         and 3
                   Else:
             (/     Divide
               .    the argument
                2   by 2

Main function:
?(-.)(-+?().
?             If
 (- )         decrementing
   .          the argument
              is truthy (nonzero):
     (-        Chain these functions together:
       +        Increment
        ?       Call current function recursively
         ()     Call previous function
           .   and apply to the argument

The use of the chain macro may be easier to understand in Thimble, HBL's ungolfed companion language:
(-+?().)
=>
(chain inc recur prev arg1)
=>
(inc (recur (prev arg1)))

rusty_deque, 85 bytes
{dup~{3~*~1~+~}~{2~swap~/~}~{dup~2~swap~%~0~=~}~ite~}~{dup~1~<~}~while~pop~len~lb~ll~

Explanation
# start with n on the right of the deque
{                                   # begin while block
 dup~                               # dup to get next step
     {3~*~1~+~}~                    # when n is odd, push 3*n+1
     {2~swap~/~}~                   # when n is even, push n/2
     {dup~2~swap~%~0~=~}~           # conditional, is n even?
     ite~                           # if
}~                                  # end while block
  {dup~1~<~}~ while~                # while n > 1
                    pop~            # delete extra 1
                        len~ lb~    # convert the stack to a list
                                ll~ # pop list, push len of list

Rust, 67 bytes
|mut n|{let mut u=0;while n!=1{if n%2==0{n/=2}else{n=3*n+1}u+=1}u};

Try it online!
Nice way of practicing rust

Knight, 37 bytes
;=n+0P;=iT;W-1=nI%n 2+1*3n/n 2=i+1iOi

Try it online!

><> (Fish), 31 bytes
:1=?\::2%?\2,
;nl~/i+1*3/
|.!0/

Try it

Punchtape, 405 bytes & Punchcode, 50 bytes
I did this just for fun and showcase
Punchtape is an esoteric language trying to imitate punched tape, a form of data storage widely used by computers in the 1950s and 1960s.
Punchcode is the compiled (UTF-8) form of it.
There is no compiler or interpreter publicly accessible at the moment because I am still working on it.
punchtape
START|
O-OO-|
OOOO-|
----O|
---O-|
----O|
-----|
----O|
---O-|
----O|
---OO|
----O|
----O|
----O|
O--OO|
----O|
-----|
----O|
-----|
OOOO-|
---OO|
-----|
-OO--|
---O-|
O---O|
OOO-O|
--OO-|
--O-O|
OO-OO|
O--O-|
O--OO|
OOO-O|
--OOO|
--O--|
O-O--|
---O-|
-O--O|
OO-OO|
OOOO-|
---OO|
-----|
O----|
--OO-|
O--OO|
---O-|
--OOO|
-OO-O|
O-O--|
---O-|
-O--O|
-O-OO|

punchcode
(This contains characters that a lot of web browsers and fonts dont display or display them in a way that is inconvenient for showing code. To combat this, all characters have been shifted 32 times byte-wise to show as basic latin characters.)
6>!"! !"!#!!!3! ! ># ,"1=&%;23='$4");># 0&3"'-4")+

Here is the original form of the code, if you are curious:

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


text:
When is a giraffe not a giraffe?
I hope this kind of "riddle" is ontopic in Programming Puzzles & Code Golf.
Give an example of a situation where the C# method below returns false:
public class Giraffe : Animal
{
  public bool Test()
  {
    return this is Giraffe;
  }
}

Rules: The code lines above must not be changed in any way, but you would put the code into an application so that the "project" compiles and the method is called. When run, the method must return false. The solution I have in mind, does not emit its own IL at run-time or similar "exotic" things, it's an ordinary instance method call.

By "the method is called", do you mean to say that Giraffe giraffe = new Giraffe(); giraffe.Test(); must occur somehow so that the line in that method is, in fact, executed?

@JesseC.Slicer Yes, in the solution I have in mind, that line does occur. Of course, it could be interesting to see other solutions that I haven't thought of, too. So if you have something, do post it!

Well, my simple solution looks more like Animal giraffe = new Giraffe(); giraffe.Test(); and the parent class Animal has a Test() method which returns false. That's cheating a bit as it calls the parent class method rather than Giraffe's. But the call site looks the same.

@JesseC.Slicer Ah, I see. I would argue that with your "solution" it is not the "method below" (as it says in my problem) that returns false, so I wouldn't say it was a full solution. But interesting still. My solution does not have any method hiding (hint), but as I said, other solutions could be interesting too.

Yay, found it!
public class Animal
{
    public class Giraffe { } // 1
}
public class Giraffe : Animal // 2
{
    public bool Test()
    {
        return this is Giraffe;
    }
}

Since Giraffe 1 is a member of Animal, and Giraffe 2 is one level further out, the name Giraffe in the is test refers to the former (section 7.6.2 in the C# 5 spec).
Visual Studio shows a warning for this is Giraffe:

The given expression is never of the provided type

which is obviously true, since it's the whole point :)
You cannot put Giraffe 1 directly inside Giraffe 2, because

member names cannot be the same as their enclosing type

– but such a rule does not exist for derived classes.
Neat problem, took me a while.

Well played sir

Yes, this was the solution I had in mind! So there are two types, one nested TheNamespace.Animal.Giraffe which because of inheritance can also be called  TheNamespace.Giraffe.Giraffe, and one non-nested  TheNamespace.Giraffe. Your reference to the C# spec is relevant! You can get rid of the compiler warning. Just change the nested type of the base class from class to interface. In that case someone might derive further from the non-nested Giraffe and implement the nested Giraffe as well, so in that case the compiler can't complain; it's a "fair" type check.

I don't understand this solution — that may be because I don't know C# much. I don't like this playing on names. I find the solution of @JesseC.Slicer much cleverer.

source: Stack Exchange

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

sort: votes


text:
Speak digits from 0 to 9 aloud
Inspired by this question from electronics.SE, here's a challenge for you:
Write a program or subroutine that takes in a sequence of decimal digits (0 to 9) and speaks them aloud, without using an existing speech synthesis tool.
Input:
You may ask for the input digits to be provided in any reasonable format, e.g. as a string of ASCII digits, an array of integers, a BCD-encoded number, etc.  If your solution is an executable program, you may take the input as a command line parameter, read it from standard input, or obtain it in any other reasonable manner.
Your program must be able to speak at least eight digits per invocation.  You may assume that the first digit is not zero, unless it is the only digit.
Output:
Your program may either speak the numbers directly using an audio device, or it may output a playable sound file.  The output file, if any, may be in any standard audio format, or it may consist of raw sample data.  If you output raw sample data, please note the appropriate parameters for playback (sample rate, bits per sample, endianness, signed/unsigned, # of channels).  Formats supported by aplay are preferred.
You are free to decide the details on how the numbers will be spoken, but your output should consist of English language digits spoken in a manner understandable to a typical English speaker, and it should be clear enough for the listener to be able to accurately transcribe a spoken eight-digit random number.  No, just beeping n times doesn't count.  Don't forget to include pauses between the digits.
Scoring:
Standard code-golf scoring rules apply: Your score is the length of your code in bytes or, if your code is written in Unicode text, in Unicode characters.  Lowest score wins.  Any language goes.
As the original question on electronics.SE was about embedded programming, I felt it would be appropriate to toss a bone to authors using low-level languages: if your solution is written in a compiled language, you may choose to count the length of the compiled executable file in bytes as your score.  (Yes, precompiled bytecode, such as a Java .class file, is OK too.)  If you choose to make use of this option, please include a copy of the compiled executable in your answer (e.g. as a hex dump) along with your source code and the compiler version and options you used to generate it.
An honorable mention, along with a +50 rep bounty, will be granted to the first answer that also meets the criteria of the original question, i.e. is capable of running on an embedded MCU with 4 kb of flash and 1 kb of SRAM.
Restrictions:
You may not make use of any files or network resources that are not part of your chosen language's standard runtime environment, unless you count the length of said files or resources as part of your score.  (This is to disallow e.g. loading audio samples from the web.)
You may also not use any pre-existing speech synthesis tools or libraries or compilations of audio data (unless you also count their size as part of your score), even if they're included in your chosen language's standard runtime environment.

Ps. I may post a solution of my own later, if I manage to make it produce something that actually sounds understandable. Don't be shy of posting your own, though; at this point, any answer is a good answer.

Are we allowed to download a database of spoken digits (and count its size towards the score) or we have to record our own voice? I doubt I can generate speech samples algorithmically.

umm... the "output" section does not specify we must output speech samples. Are we allowed to simply beep ten times?

@PeterTaylor: If you count their size as part of your score, it's OK. I was just worried that there might be some system out there that has audio samples of digits buried somewhere in its standard runtime environment.

@JanDvorak: No, because that would not really be "understandable to a typical English speaker" without an explanation.

@IlmariKaronen I believe "beep---beep-beep---beeeeeep---beep-beep-beep-beep" is quite understandable - especially if I encode a short pause after a group of five.

@JanDvorak: Maybe if you're R2D2. But no, that's not the intent of the challenge. I've edited the rules to try to clarify them on this point (and the one brought up by Peter).

So AppleScript's say command is out of the question?

@arshajii it sounds like a pre-existing speech synthesis tool. So, yes.

Since there seems to be a steady stream of people who don't read the question to the end and post trivial wrappers around heavyweight libraries, it might be worth editing to put even more emphasis on the "Do it yourself" aspect.

ruby - 3710 = 90 characters code + 3620 bytes data
require'zlib'
$><<$*[0].chars.map{|x|Zlib::Inflate.inflate File.open(x).read}.join(?0*5e3)

input: a single command line argument, the number to read
output: raw sound data, PCM 8bit/8kHz
This can read any input string, as long as

it only contains characters that are valid file names. for only four chars, you can enlarge that set to all characters.
you have the neccessary files.
why oh you space dee oh en apostrophe tee space em i en dee space tee aitch i es period

5e3 encodes the pause between two words. Here, 5ksamples ~= 0.6s. Tweak as desired.
Now, the tricky part is to get the sample files in 4K and yet be able to decompress them easily and in sufficient quality. Here is how I got them:

Take a Text-to-speech engine able to produce sound files. Wikipedia has one.
Feed it a text containing all digits, ideally close together. I used http://en.wikipedia.org/wiki/Base_13
Downsample.
Cut out each part in a sound editor.
Save as a raw file.
Decimate each sample (discard low-order bits).
Deflate.

Now, one has to choose a sample rate and decimation amount. Too much, and the sound won't be understandable. Too little, and you don't fit. I have settled for 8kHz/3b. There they are: https://github.com/honnza/drops/raw/master/digits.zip

8KHz * 4b/sample and higher quality - too big
8KHz * 3b/sample - low quality, but it fits into 4K
8KHz * 2b/sample - kch kchhhhhhhhh [not understandable]
2KHz * 8b/sample - too big
2KHz * 3b/sample - kch kchhhhhhhhh
1KHz * 8b/sample - kch kchhhhhhhhh

Here's the decimation script:
require'zlib'
Dir.glob "*.raw" do |fname|
  File.open fname[/\d/], "wb" do |out|
    File.open fname do |input|
      bytes = input.bytes.to_a
      bytes.map! {|x|x&0xE0}
      dfl = Zlib::Deflate.deflate(bytes.pack("C*"),9)
      dfl.each_byte do |byte|
        out.print byte.chr
      end
      puts "done #{fname}: #{dfl.size}"
    end
  end
end

As for the original challenge: there are 476 bytes of space for code and the file table. This might be slightly too much depending on how tiny we can get with a DEFLATE library. If neccessary, we can cut a few corners here and there by cropping the audio samples a bit more aggresively. [fo:r] or [o:] doesn't really matter but it saves bytes. I have been somewhat benevolent when cropping the numbers. Also, a different decimation scheme or sacrificing some decimation for downsampling might help - I'll toy with these later. Also, dropping the DEFLATE headers might save a tiny amount of space.
Concatenating sound samples is quite easy, but 4K is a little cramped. If you are not bound by 4k space, I suggest less decimation. 4 bits per sample actually fares quite well and is only slightly bigger.

+1, not bad. The clarity is pretty marginal, though: I tried transcribing a few random numbers and got about a 70% success rate. (I was hoping for something closer to 99%.) I'm also still a little bit on the fence about the honorable mention thing: while you've made a pretty good argument that 4K could be attainable this way, you haven't actually demonstrated it. Even if you ditched ruby for C (which seems easy enough to do; I'd be willing to take that part on faith), could you really fit a DEFLATE decoder in the remaining flash space? Plus, as I noted, the sound quality is pretty bad.

Ps. A few tips on better compression: You could pad all the samples to a fixed length with null bytes (which should compress well) and concatenate them into one compressed file, then decompress and slice it. Also, the KZIP trick from this answer could give you better DEFLATE compression. Finally, try editing the combined sound file to replace equivalent phonemes with exact copies.

well, the original sound samples were not exactly understandable either IMO - the downsampling did little damage to that. The smallest DEFLATE library I know - the first one linked by wikipeda - weighs about 500b. Frankly, do you want me to port the inflater to that specific device? I might get to it actually, but I've never coded for ARM before.

I'm pretty surprised about the 70% success rate - I've found the numbers to be easy to understand. Which digits did you confuse the most?

Porting it to a Cortex M0 is probably a bit too much to ask (although if you could do that, that'd be awesome!), but I do think that a stand-alone binary (+ data files, if any) fitting under 4k would seem a reasonable demonstration. (No need to statically link in libc for file I/O, since you wouldn't need that on an embedded device, but the DEFLATE code should certainly be counted.) Basically, something that you could post as an answer to the original question on electronics.SE and confidently say "if you compile this for your device, I bet it'll fit".

As for the errors, looking at my tests, it seems I consistently transcribed your "1" as a "9" and vice versa. Your "8" also sounds a bit like a "6" to me, and your "3" like a "2". (I bet I could learn to transcribe them correctly with practice, but that's again really outside the scope of the challenge, for the same reason that just emitting beeps is.)

How well do you fare transcribing digits from other sources? I think that beating native speakers in terms of legibility is beyond the scope of this challenge. I can upload the undecimated digit sounds. If they aren't easier to understand for you, it's kinda futile to try to develop a better compression scheme. The digits you've mentioned seem pretty distinct to me - but try these anyways: https://github.com/honnza/drops/raw/master/digits-hq.zip

I tried to download the HQ samples, but your link gives me a 404 error. :( Anyway, I just tried it with this speech synthesizer and I haven't made any transcription errors so far.

I'm curious that you don't list any 4 kHz results. 4 kHz at 5 bits would be smaller than 8 kHz at 3 bits.

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


text:
Flip the commented-out code
This puzzle works for any programming language that has the same // single-line and /* ... */ multi-line comments that C++, C# and Java do.
You are debugging an application. You find a fishy block of code, which you comment out and replace with some new code:
/*
code block A
*/
code block B

After some debugging, you find that you need to step through block A again to see how it worked. This requires quite a lot of cursor movement:
                ← remove “/*” here
code block A
/*              ← change “*/” to “/*” here
code block B
*/              ← add “*/” here

This is very laborious if you need to keep switching between block A and block B. So you decide to find a better way.
Place combinations of asterisks and slashes before block A, between the blocks, and after block B, such that you can flip between block A and block B by adding/removing only one character in one place. You may assume that the code blocks A and B do not contain any /* or */.
There are two possible solutions.

Or use the pre-processor to do the job it was designed for! :-)

Toggle commented out blocks by adding/removing the last slash on the first line:
/**/
code block A
/*/
code block B
/**/

Bonus solution, toggle this one by adding/removing the first slash on the first line:
//*
code block A
/*/
code block B
/**/

Double-bonus: The last line in each case may be replaced by //*/, giving four distinct solutions :)

It is your second solution that I’ve always used, and bobthecow’s variation on it that I knew of. Congratulations for finding another solution I hadn’t yet encountered! :)