text:
Let us create a sonnet quine!
There are programs that will output its source code to standard output and do nothing else. They also access no external output. This type of program is known as a quine, and is a common code challenge.
There are poems that have the rhyme scheme a-b-a-b, c-d-c-d, e-f-e-f, g-g. They have 14 lines. They are usually recited in iambic pentameter. They are called sonnets.
You are to write a program/poem that is both a quine and a sonnet.

When saying lines, it is recommended that you only say all characters except for: whitespace and ,()[]_"'. This is flexible depending on the language though.
Iambic Pentameter means 10 syllables, starting unstressed, and then alternating between stressed and unstressed. This is optional, but will mean more votes.
Comments are discouraged, especially to complete rhymes (although comments are very much encouraged if they can be incorporated with the code in the poem in a way that produces dramatic effect.)
Cruft is discouraged.

Voters, use the four above guidelines when voting. This is a popularity contest, so the program with the most votes wins.

This is too easy for languages like Javascript, which (function(){return'('+arguments.callee+')()';})() is a quine. Adding garbage after the return is enough.

I was going to attempt this one, but the restrictions imposed by creating a quine (in most languages) make it too difficult to output any kind of meaningful sonnet. Therefore the question isn't very interesting, since the sonnet will just be rhyming characters such as / and - (slash and dash).

@grovesNL You could create a different sonnet challenge.

@IsmaelMiguel That isn't considered a quine, since you are accessing an external resource (namely, the source code.)

@PyRulez I wasn't trying to be rude. I'm just offering some feedback, which may especially relevant if there aren't many responses for that reason.

Actually, I'm reading the arguments passed to the function. From there, I access the function itself and take the source code. It accesses itself.

@grovesNL I was serious. It would be sort of odd to completely change the question now, but if you have an idea for a sonnet challenge go ahead. I wasn't trying to be rude either.

@IsmaelMiguel From wikipedia, it says quines can't use input.

@PyRulez Is there any input in it?

Code Challenge, Popularity Contest and Code Golf are mutually exclusive. You've described a popularity contest in the question text, so the code challenge tag doesn't need to be there.

@IsmaelMiguel: I guess it's not a quine if the restriction is "the code cannot read its own source code in whatever manner"

It cannot read it's source code from external sources. The var arguments is an internal var to the function itself.

Wait iambic pentameter is not required? So 10 syllables per line is not required?

I don't think that this question has lived up to our sites standards in the past 3 years.  1) There is no objective definition of sonnet, making this question rather unclear.  2) There is no judging criterion other than "most creative" making this question without a proper winning criterion.  In the past it was common practice for anything to go in terms of a pop-con but that has changed.  I am going to Vote to close as unclear until this challenge is clarified.

While I undersand the intention behind giving people some leeway when it comes to pronounciation, it means that the validity of any answer is debatable, ultimately making the challenge unclear.

@Dennis that's why its a popularity contest.

Popularity contest no longer means anything goes. All challenges need an objective validity criterion.

Ruby
s = [[/t{1}he_way/,'to_a'],[/\*j{1}ewel/,'*rule']].to_a
puts <<'-'.*(2).tap { |code| s.each { |rule| code.sub! *rule } }, '-'
s = [[/t{1}he_way/,'to_a'],[/\*j{1}ewel/,'*rule']].the_way
puts <<'-'.*(2).tap { |code| s.each { |rule| code.sub! *jewel } }, '-'
-
s = [[/t{1}he_curse/,'reverse'],[/\*c{1}raze/,'*phrase']].reverse
puts <<'-'.*(2).tap { |code| s.each { |phrase| code.sub! *phrase } }, '-'
s = [[/t{1}he_curse/,'reverse'],[/\*c{1}raze/,'*phrase']].the_curse
puts <<'-'.*(2).tap { |code| s.each { |phrase| code.sub! *craze } }, '-'
-
s = [[/r{1}eject/,'collect'],[/\*b{1}ird/,'*word']].collect
puts <<'-'.*(2).tap { |code| s.each { |word| code.sub! *word } }, '-'
s = [[/r{1}eject/,'collect'],[/\*b{1}ird/,'*word']].reject
puts <<'-'.*(2).tap { |code| s.each { |word| code.sub! *bird } }, '-'
-
puts <<'-'.*(2).tap { |code| [[/\*l{1}augh/,'*half']].each { |half| code.sub! *half } }, '-'
puts <<'-'.*(2).tap { |code| [[/\*l{1}augh/,'*half']].each { |half| code.sub! *laugh } }, '-'
-

Don't pronounce the dashes, they're just there to delimit stanzas. Scansion's not perfect but decent.

+1 "Reverse the Curse!" would be a catchy title. I'm not crazy about the phrasing, but I got more than half a laugh out of this.


text:
Arranging pins on a microchip
Since no one has posted a "good quality question" recently, i feel it is my duty to...
Task:

You work at an electronics company in the design department. The designers that work with you have asked you to make a program that will calculate the optimum configuration of pins on a microchip they are designing. With your ninja golfing skills, you are confident you can handle it.

Your company also has these requirements for each chip:

The chips your company makes are known as TQFP, they have pins on each edge, but none in the middle.
Each chip must be square, and have the same number of pins on each side.
If the chip doesn't have enough pins to be square, pins will be added.

Extra pins are either a ground or voltage supply pin.
Half are ground, half are voltage supply.
If there is an odd number of extra pins, the odd one out is ground

Your program will take input as a single integer, which is the minimum number of pins the manufacturing needs. You will then output 4 integers:

The number of pins (total)
The number of pins per side
The number of ground pins added
The number of voltage supply pins added

Rules:

You can use any language
This is code-golf, to the shortest answer in bytes wins
Bonus: -50 for printing an ASCII chip:

Something like this:
 +++++
 +   +
 +   +
 +   +
 +++++

(For example with an input of 20)

By odd one out do you mean that if we need to add an odd number of pins that #ground = #voltagesupply + 1 or vice-versa?

@Kaya no, you have to add enough to make it divisible by 4

You may want to add clarification for a point that confused me at first: the pins are at the perimeter of the square, not throughout the square area.

@TheDoctor you misunderstand my query. Let me rephrase: upon input 3 should the program output 4,1,1,0 or 4,1,0,1?

mmm ...chip is an ASCII chip

@belisarius, http://meta.codegolf.stackexchange.com/a/1070/194

@PeterTaylor Yep, I know. But "draw a chip" is a little vague.

Everyone - I was rushed.

@kaya 4,1,1,0

One does have to grin at the sheer bravado of posting a question in a rush and then making bold claims that 'no one has posted a "good quality question" recently'.  :D

@JonathanVanMatre I just have seen too many downvoted/closed questions recently. I was getting a little bored.

@JonathanVanMatre, I'm not sure whether to feel insulted. I'm also not sure whether to vote to close this as little more than a duplicate of Find next multiple of 32.

@TheDoctor, if you're bored by seeing downvoted questions, you could visit the sandbox and try to implement one of the better looking ones there. That way you'll see whether the spec is missing corner cases, and you can help to improve it before it gets posted on the main site.

Why does your example ASCII chip for n=20 pins have 16 pins? If we are supposed to draw a chip with n-4 pins instead of n then what do we draw in the case where n<=4?

@Kaya, it looks to me like it only has 12 pins, because the question clearly states that the pins are on the sides, so the + characters at the corners shouldn't count.

All fine and dandy barring that it doesn't address the awkward edge case when n<=4.

It would have been wise to make the example ASCII chip have ground and voltage supply pins, and display them differently. As far as I can tell, none of the other implementations draws them differently from the standard pins.

@Kaya for the ASCII chip, each corner has 2 pins

APL, 54 chars/bytes* – 50 = score 4
“Take this, Golfscript!” special edition
{t s(⌈h)(⌊h←2÷⍨⍵-⍨t←4×s),⊂' +'[1+∘.{∨/⍺⍵∊1s}⍨⍳s←⌈⍵÷4]}

Takes a number as input and returns the required output. Dialect is Dyalog with ⎕IO⎕ML←1 3
Explanation
{                        s←⌈⍵÷4 }  divide the # of pins by 4, take the ceiling and call it s
            ∘.{       }⍨⍳s         for each couple of naturals up to s compute a table with:
               ∨/⍺⍵∊1s             1 if either one of the two numbers is 1 or s, 0 otherwise
    ⊂' +'[1+                   ]   convert the 0 and 1s to space and + and enclose the table
                                   then...
                  t←4×s            multiply the pins per side by 4 and call it t (for total)
          h←2÷⍨⍵-⍨t                subtract the # of pins from it and divide by 2, call it h
 t s(⌈h)(⌊h            )           make a vector with t, s, the ceiling of h, and its floor,
                        ,——        and prepend it to the previously enclosed table of chars.

Examples
    {t s(⌈h)(⌊h←2÷⍨⍵-⍨t←4×s),⊂' +'[1+∘.{∨/⍺⍵∊1s}⍨⍳s←⌈⍵÷4]} 0
0 0 0 0
    {t s(⌈h)(⌊h←2÷⍨⍵-⍨t←4×s),⊂' +'[1+∘.{∨/⍺⍵∊1s}⍨⍳s←⌈⍵÷4]} 1
4 1 2 1  +
    {t s(⌈h)(⌊h←2÷⍨⍵-⍨t←4×s),⊂' +'[1+∘.{∨/⍺⍵∊1s}⍨⍳s←⌈⍵÷4]} 2
4 1 1 1  +
    {t s(⌈h)(⌊h←2÷⍨⍵-⍨t←4×s),⊂' +'[1+∘.{∨/⍺⍵∊1s}⍨⍳s←⌈⍵÷4]} 3
4 1 1 0  +
    {t s(⌈h)(⌊h←2÷⍨⍵-⍨t←4×s),⊂' +'[1+∘.{∨/⍺⍵∊1s}⍨⍳s←⌈⍵÷4]} 4
4 1 0 0  +
    {t s(⌈h)(⌊h←2÷⍨⍵-⍨t←4×s),⊂' +'[1+∘.{∨/⍺⍵∊1s}⍨⍳s←⌈⍵÷4]} 5
8 2 2 1  ++
         ++
    {t s(⌈h)(⌊h←2÷⍨⍵-⍨t←4×s),⊂' +'[1+∘.{∨/⍺⍵∊1s}⍨⍳s←⌈⍵÷4]} 6
8 2 1 1  ++
         ++
    {t s(⌈h)(⌊h←2÷⍨⍵-⍨t←4×s),⊂' +'[1+∘.{∨/⍺⍵∊1s}⍨⍳s←⌈⍵÷4]} 7
8 2 1 0  ++
         ++
    {t s(⌈h)(⌊h←2÷⍨⍵-⍨t←4×s),⊂' +'[1+∘.{∨/⍺⍵∊1s}⍨⍳s←⌈⍵÷4]} 8
8 2 0 0  ++
         ++
    {t s(⌈h)(⌊h←2÷⍨⍵-⍨t←4×s),⊂' +'[1+∘.{∨/⍺⍵∊1s}⍨⍳s←⌈⍵÷4]} 9
12 3 2 1  +++
          + +
          +++
    {t s(⌈h)(⌊h←2÷⍨⍵-⍨t←4×s),⊂' +'[1+∘.{∨/⍺⍵∊1s}⍨⍳s←⌈⍵÷4]} 13
16 4 2 1  ++++
          +  +
          +  +
          ++++

*: Dyalog supports its own (legacy) single byte charset, where the APL symbols are mapped to the upper 128 byte values. Therefore the entire code can be stored in 54 bytes if needed.

Python: 64 53 46 bytes
x=input()
m=x+3&~3
t=m-x
print m,m/4,t-t/2,t/2

Second Third attempt seems pretty minimal. Thanks for the help.
First attempt seems sort of long, we'll see what an hour or two of mulling it over will shave off of the byte count. Could also probably make it shorter if a function is allowed instead of program.
> python chip.py
9
(12, 3, 2, 1)

Also made a version that prints chips, seems like the -50 isn't worth it in python. Total score of 102-50=52.
x=input()
m=x+3&~3
n=m/4
t=m-x
s=['+'*-~n]
print'\n'.join(s+['+'+' '*~-n+'+']*~-n+s+[`m,n,t-t/2,t/2`])

Example:
> python chip.py
9
++++
+  +
+  +
++++
(12, 3, 2, 1)

can't y=(4*m-x)/2 be written as y=2*m-x/2 (saving two bytes)?

Isn't 9 enough pins for it to be square (3 by 3)? Or am I misunderstanding the question?

@grovesNL most square chips I have seen only have pins round the edge, so the number of pins has to be divisible by 4. That's how I understood the question.

@steveverrill I see. I interpreted it as pins contained throughout a square area, not the perimeter. Thanks.

Also you can write (4*m-x)-y as 4*m-x-y (two bytes)

more golfing: m=x/4 if x%4:m+=1 can be written as n=x%4 m=x/4+n/n

And add the code t=4*m-x and replace all further instances of (4*m-x) with t.

Remove the brackets in print to save another byte!

Julia, 62 61 56 bytes
m(x)=(s=iceil(x/4);p=4s-x;(4s,s,iceil(p/2),ifloor(p/2)))

Very straightforward. And now down to 56 thanks to gggg's sharp eyes.
Outputs:
In [14]:
    m(9),m(6),m(71),m(1),m(3)
Out[14]:
    ((12,3,2,1),(8,2,1,1),(72,18,1,0),(4,1,2,1),(4,1,1,0))

The ASCII chip bonus isn't worth the bytes it costs, but since I made it, here's all 190 bytes of it. Edit: I made the chip drawing before OP posted an example chip , so I'm sticking with my method. I think it looks better than plus signs, anyway.
m(x)=begin s=iceil(x/4)
p=4s-x
g=iceil(p/2)
v=ifloor(p/2)
b={x in[1,s]||y in[1,s+1]?"o":"."for x=1:s,y=1:s+1}
if g>0 b[1,1:g]="G" end
if v>0 b[s,s+2-v:s+1]="V" end
print(b,'\n')
return 4s,s,g,v end

m(29)

G G o o o o o o o
o . . . . . . . o
o . . . . . . . o
o . . . . . . . o
o . . . . . . . o
o . . . . . . . o
o . . . . . . . o
o o o o o o o o V

Out[7]:
(32,8,2,1)

This version of the chip gets it down to 115, which is still too long for the bonus to be worthwhile. And it requires the "corners have two pins even though one is shown" assumption of OP's example. I prefer my corrected version above which shows the exact number of each type of pin.
m(x)=((s=iceil(x/4);p=4s-x);b={x in[1,s]||y in[1,s]?"o":"."for x=1:s,y=1:s};print(b);(4s,s,iceil(p/2),ifloor(p/2)))

Question posters of the future, take note: bonuses often serve only to increase the advantage of terse languages.

m(x)=(s=iceil(x/4);p=4s-x;(4s,s,iceil(p/2),ifloor(p/2))) is shorter, since Julia returns the result of the last statement.

p(m,n)=(a="+";b="\n";c=a^m*b;c*(a*" "^(m-2)*a*b)^n*c) returns the ops pattern in a string the OPs pattern in 46 characters after the =, might be able to work it in for a small bonus if you can find any more efficiency.

@gggg The p(m,n) function also requires a print statement to display correctly, so in the end my array constructor was the cheaper approach once you take out the necessary steps for the G and V pins...but still too long to get the bonus.

GolfScript, score 5 (55 characters - 50 bonus)
~:^3+3~&.4/:&1$^-.)2/\2/]p&)'+'*n+'+'&(' '*'+'++n+&(*1$

The input is given on STDIN. The first part (until ]p) does the calculation while the rest is for the bonus.
Examples (run online):
> 20
[20 5 0 0]
++++++
+    +
+    +
+    +
+    +
++++++

> 9
[12 3 2 1]
++++
+  +
+  +
++++

Perl, 72 bytes
The input number is expected in STDIN, the result is written to STDOUT.
$_=<>;$==$_/4+!!($_%4);$a=4*$=-$_;@a=(4*$=,$=,$a-($-=$a/2),$-);print"@a"

Test:
echo 4 | perl a.pl
4 1 0 0

echo 5 | perl a.pl
8 2 2 1

echo 6 | perl a.pl
8 2 1 1

echo 7 | perl a.pl
8 2 1 0

Ungolfed:
$_=<>; # read input number from STDIN
$= = $_ / 4 + !!($_ % 4); # tricky way for ceil($_ % 4)
$a = 4 * $= - $_;         # extra pins in $a
@a = (4 * $=,             # total
      $=,                 # each side
      $a - ($- = $a / 2), # ground, tricky way for $a - floor($a/2)
      $-                  # voltage
);
print "@a"                # print result, separated by spaces

a.pl == APL??  :)

J - 71 66 char -50 = 16 pts
Saves a bunch of bytes with the 50 bonus, so let's do that.
(((>.,<.)@-:@-@],~-,[:#2:1!:2~' +'{~1,~1,1,.~1,.0$~2#2-~-%4:)_4&|)

Some key bits:

_4&| - Take the input modulo -4: it's just like taking it mod 4, but you go into the range (-4,0].
(>.,<.)@-:@-@] - Negate the residue mod -4 from before, halve it (-:), and take the ceiling (>.) and the floor (<.).
1,~1,1,.~1,.0$~2# - We make a square array of zeroes, and then pin ones all around it: in front (,.), behind (,.~), on top (,) and below (,~).
[:#2:1!:2~' +'{~ - After constructing the square array the way we like it, we use its values to select ({) out of the characters ' ' and '+', and then we print the matrix with 2:1!:2~. Finally, we get the original number back (the number of pins per side) with the length.

Usage:
   (((>.,<.)@-:@-@],~-,[:#2:1!:2~' +'{~1,~1,1,.~1,.0$~2#2-~-%4:)_4&|) 20
+++++
+   +
+   +
+   +
+++++
20 5 0 0
   (((>.,<.)@-:@-@],~-,[:#2:1!:2~' +'{~1,~1,1,.~1,.0$~2#2-~-%4:)_4&|) 9
+++
+ +
+++
12 3 2 1

The version without the ASCII-drawing portion is 30 characters:
   (((>.,<.)@-:@-@],~-,-%4:)_4&|) 86
88 22 1 1

+1 (>.,<.) bah, I knew a stack-based language would take this one away from Python. @-@ I like your way of generating the chip.

@Kaya J isn't stack-based, actually, it just has a very terse and high-level style. Though I imagine Golfscript would have a field day with this.

Python (103):
from math import*
a=int(raw_input());c=ceil(a**.5);b=c**2;z=(b-a)/2;d=ceil(z);e=floor(z);print (b,c,d,e)

Not the shortest, but it does what it's supposed to.

I initially interpreted the question this way too, see groveNL's comment on the question above: You may want to add clarification for a point that confused me at first: the pins are at the perimeter of the square, not throughout the square area. It seems the goal is to find the next multiple of four rather than the next perfect square.

K - 68 char -50 = 18 pts
This solution mimics the J methods somewhat, but has an APL-like way of shaving off characters.
{`0:(" +"1,|1,)'+r#,1 0,|~!r:-2+q:_(x-:m:x!-4)%4;x,q,-1 1*_.5 -.5*m}

Explained:

x-:m:x!-4 - Take x mod -4, putting it into the range (-4,0]. Now, assign this to m (for modulus), and reassign x to x subtract m.
r:-2+q:_(x)%4 - Divide x by 4 and floor it, converting it from unnecessary float to integer. Assign this to q, and assign two less than this to r.
1 0,|~!r - Take the integers less than r, starting from 0. Logical negate every integer, leaving a 1 in the 0 place and 0 everywhere else. Reverse the list, and then prepend 1 0. Now, the list will be r+2 = q items long, and the first and last are a 1.
+r#, - Make r copies of this list, and transpose the resulting matrix, which is now r wide and q high.
`0:(" +"1,|1,)' - Append 1 to the front and back of each row, and then use the placement of the 0s and 1s to select characters out of " +". This creates an ASCII chip, which we print out to console with `0:.
_.5 -.5*m - Take m from before, halve it, and then floor it and its negation. K doesn't have a ceiling function, so you have to emulate ceiling by flooring the negative, and negating that again.
x,q,-1 1* - Flip the sign on the negative number of the two, and then append x and q from before to the list. This then goes on to be the return value.

Usage:
  {`0:(" +"1,|1,)'+r#,1 0,|~!r:-2+q:_(x-:m:x!-4)%4;x,q,-1 1*_.5 -.5*m} 20
+++++
+   +
+   +
+   +
+++++
20 5 0 0
  {`0:(" +"1,|1,)'+r#,1 0,|~!r:-2+q:_(x-:m:x!-4)%4;x,q,-1 1*_.5 -.5*m} 9
+++
+ +
+++
12 3 2 1

The version with no ASCII drawing is 34 characters:
  {x,_%[x-:m;4],-1 1*_.5 -.5*m:x!-4} 86
88 22 1 1

source: Stack Exchange

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

sort: votes


text:
Why isn't it ending?
Your task: To write a program that should obviously terminate, but it never (to the extent of a computer crash) does. Make it look like it should perform a simple task: adding numbers, printing something,... But it just gets caught in an infinite loop.
Try to make your program very clear and simple, while it actually will get stuck in an unforeseen loop. Voters: judge the answers on how "underhanded" they are!
This is a popularity contest: Be creative!

Could someone please explain what I can do to make the question less broad? I am new here. Thank you!

This is just going to be a big list of typos and beginner's mistakes which cause loops.

Interesting question, but I haven't seen any truly creative answers yet. I promise up votes to anyone who doesn't use loops or obvious recursion!

@ValekHalfHeart Does my answer qualify? ;) There is a loop... but I wouldn't call the bug obvious.

@ValekHalfHeart No loops, no recursions: http://codegolf.stackexchange.com/a/24391/14901.

http://codegolf.stackexchange.com/questions/24304/why-isnt-it-ending/24645#24645

I don't know if this counts, but my Microsoft Office is behaving exactly like this at the moment.

You have just described every FORTRAN program I have look at.

Did anybody see the PostScript answer? It does not use floating-point precision, but self-mutilating code.

I feel like I've done this so many times by accident in Awk and now I can't think of a way to make it happen on purpose.

I'm voting to close this question as off-topic because underhanded challenges are no-longer on-topic here. http://meta.codegolf.stackexchange.com/a/8326/20469

Javascript
var x=prompt('Enter a value under 100');
while (x != 100) {
  x=x+1;
}
console.log('End!');

 prompt() returns a string and the loop appends the character '1', it will never be equal to 100.

You got me with that one… the (actually) higher-voted examples are all just abusing syntax… but that one is nice!

Chrome on Kubuntu became unresponsive, hang everything and I had to hard reset :)

Similar should work on Python too

@Vlakarados, sorry about that :) you can also probably looking for the pid of the chrome tab with the most CPU usage and kill it.

Terminal hanged up as everything else, that's strange as IIRC on Win they didn't hang the system completely :) Anyway, nice one

is x considered a string so 1 is converted to a string and it's using concatenation?

@Cruncher, absolutly.

@Michael oops. Didn't see the spoiler section. It really blends in on my browser

@Vlakarados: Python won't do the implicit type conversion Javascript does. On Python, the equivalent code using raw_input or Python 3 input raises a TypeError.

@user2357112 right, I thought about it the other way around - in Python + is a concatenation operator too. Thanks for pointing out

There is not check on the fact that value is actually under 100 so it stops normally when you enter "100" :'-(

@C.Champagne instead of != you could use !== to prevent the loop from terminating when you enter 100.

Can someone please provide explanation Or some pointers for why this never terminates ?

@Sankalp, the + operator here is the string concatenation, not the addition.

C
Just a basic example program that illustrates the three different kinds of while-loops in C.
int main() {

    int x = 0;

    // Multi-statement while loops are of the form "while (condition) do { ... }" and
    // are used to execute multiple statements per loop; this is the most common form
    while (x < 10) do {
        x++;
    }

    // x is now 10

    // Null-statement while loops are of the form "while (condition) ;" and are used
    // when the expression's side effect (here, decrementing x) is all that is needed
    while (x-- > 0)
        ; // null statement

    // x is now -1

    // Single-statement while loops are of the form "while (condition) statement;"
    // and are used as a shorthand form when only a single statement is needed
    while (x > -10)
        x--;

    // x is now -10

    return 0;
}

 While loops don't have a "do" before the opening curly brace. This actually creates a do-while loop inside of the (x < 10) loop that's terminated by the following "null statement" while loop. Since x is incremented inside of the loop and then decremented in the do-while loop's condition, the inner loop never terminates, and so neither does the outer loop. The "single-statement" loop at the end is never reached.

 If you're still confused, look here (externally hosted because codegolf.SE doesn't like code blocks in spoilers).

Haha, I figured this one out before looking at the solution spoiler. :P

Why did you pass up such an excellent opportunity to use the "goes to" operator? (x --> 0)

Oh wow.  This is wonderfully evil.  Took me four reads through to find it.

This took me forever to figure out, but only because I read the comments.

@JoeZ. Way too easy. The most upvoted solution was better. That one I didn't find.

It's only easy if you're well-versed in C. Any answer on this post could be declared "too easy" by someone familiar enough with the language.

@Fraxtil Actually, it's easy if you know C, C++, Java, etc. I have no experience whatsoever with C, but I still figured this out within fifteen seconds.

@Hat Guy, Bash has the for;do and while;do syntax so I can see people getting thrown off by this, even if they're familiar with non-C/C++ languages.
http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-7.html

JavaScript
var a = true;
(function() {
  while(!a){}
  alert("infinite");
  var a = true;
})();

 Variable hoisting: JavaScript will actually grab my second definition of var a = true;, declare it at the top of the function as var a;, and modify my assignment to a = true; meaning a will be undefined at the time it enters the while loop.

Could you add a better explanation of why this never terminates? Please go into depth about "variable hoisting" :)

@Number9 I hope that helps, google has much better examples than this ;)

Holy shit this is even worse than semicolon insertion. +1!

Only trouble I see with this program is that it doesn't look like it performs a simple task... it looks like it should essentially do nothing. Maybe add an alert after the loop.

@PeterT thanks, I just tested to make sure it hung my browser, I've added your suggestion.

For anyone interested: I found a good article on JavaScript scoping and hosting which goes into deeper depth: http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html

You should change a = 1 to a = true. The code will still have the infinite loop that way, but it will be clearer that the reason is not some quirk in JavaScript conversion from ints to booleans.

C#
class Program
{
    // Expected output:
    // 20l
    // 402
    // 804
    // l608
    // 32l6
    // game over man

    static void Main()
    {
        var x = 20l;
        while (x != 6432)
        {
            Console.WriteLine(x);
            x *= 2;
        }
        Console.WriteLine("game over man");
    }
}

 The number literal in the first line of the function is not a '201', but a '20' with a lowercase 'L' (long datatype) suffix. The number will overflow pretty quickly without ever hitting 6432, but the program will keep going unless overflow checking was switched on in the build options.
 Sensibly, Visual Studio 2013 (and probably other versions too) gives you a warning for this code, recommending that you use 'L' instead of 'l'.

Oh, the l is supposed to look like a 1! I'm stupid. :\

Suggestion for improvement: replace the 1s in the expected output section with ls as well (it's easier to spot the weird character when you have real 1s to compare against)

The expected output comment is misleading part

I don't know if it's the retina display or the font, but we can easily distinguish the l on my macbook : http://imgur.com/K0UsPf6

Yeah, it does seem to be quite environment-specific. @Michael's font looks very different to the font on my home computer (http://imgur.com/PKIuJpr - Chrome, Windows 8), and the trick seems to work better on my work computer than my home computer, even though they've got quite similar specs. My phone's browser doesn't seem to show code in a fixed-pitched font, and the trick doesn't work at all on it.

@AllenGould: I considered that, but I thought it might ruin the trick if all the 1s looked odd. The single l might have a better chance of slipping by unnoticed. Maybe it would be better to tinker with the code so that there aren't any 1s in the expected output at all.

FTR, here's what it looks like on my work computer (http://imgur.com/Opfs3BH - Firefox, Windows 7). I reckon that one could even fool quite astute people.

@BenM I was thinking the opposite - if all the 1s in the code are l, you don't have anything to compare against. :)

WHY DO PEOPLE KEEP ABUSING OF CHARACTERS THAT LOOK THE SAME?

@AnonymousPi This is kind of different because the characters are actually not identical. Eta versus H is a different story though.

C
How about precision ?
int main(void)
{
    double x = 0;
    while(x != 10) x += 0.1;
    return 0;
}

 Imagine you have to store a range of integer numbers <0;3> in computer memory. There are only 4 integer numbers in this range (0,1,2,3). It's enough to use 2 bits to store that in memory.
 Now imagine you have to store a range of floating point numbers <0;3>. The problem is there is an infinite number of floating point numbers in this range. How to store infinite number of numbers ? It is impossible. We can only store finite number of numbers. This is why some numbers like 0.1 are actually different. In case of 0.1 it is 0.100000000000000006.
 It is highly recommended to not use == or != in conditions as far as you use floating point numbers.

How does this work?

Rounding errors. 0.1 is actually 0.100000000000000006 because 0.1 in binary is like 1/3 in decimal - it's binary expansion is infinite&periodic.

Not really a rounding error. Floating point values are approximate representations of a number. Performing exact comparisons between approximate values isn't going to work.

This is why you (almost) never should compare float/doubles for equality.

I was waiting to see this one. Nice.

I'll mention that a compiler is totally allowed to optimise this into int main() {}.

@R.MartinhoFernandes Don't think so, since it's an infinite loop, and the compiler can see that. Suppose the compiler can't just go removing an infinite loop there, can it?

@tomsmeding The compiler can assume that a program will eventually do some sort of I/O, volatile access, or terminate. This one clearly does none of the first two, so it "obviously" terminates. I.e. the important thing that the compiler can see here is that the loop does no observable work, not that it is infinite.

HTML / JavaScript
Imagine you have an input box in your page:
<input onfocus="if (this.value === '') alert('Input is empty!');">

And now you want to type something in it... Try in Chrome: http://jsfiddle.net/jZp4X/.

 Standard browser dialog box called with alert function is modal, so when it's displayed it takes the focus out of the text box, but when it is dismissed the text box receives the focus back.

It also works in Safari (which can't be closed at all), but I can't test now how it behaves in other browsers.

in firefox, the input doesn't have autofocus on alert close, and from the second time it offers me to not show more alerts and then I can write in the textbox normally

@Einacio I have just tested it in Opera -- the same spamming effect as in Chrome and Safari. Shame about FF. Is it the only one with the resistance? How about IE? BTW, option to stop spamming with alert dialogs I consider as Ctrl+C in console.

Nice one. +1 for no loops or recursion.

I face the same problems as Einacio with Chrome 33 and IE 11.

No loops in either Firefox or Chrome. FF shows the alert once when the dialog is clicked, you dismiss it and that's the end of it. Can click it again to repeat. Chrome does the same, but leaves the box focused, and you can even type in it. Sorry, maybe on older versions this was a problem, but not anymore.

@romkyns It works as expected on my newest Chrome 33.0.1750.152 on Mac, in Safari 7.0.2 and in Opera 20.0.1387.77. As you may see all the versions are up to date. Maybe the issue is in operating system?

IE11 works exactly the same as Chrome for me. I think you've inadvertently found an example of something that works one way on every modern browser on Mac, and a different way on every modern browser on Windows!

ValekHalfHeart: Actually this is a loop. Commonly called event loop. :p

Works normally (no loops) on MSIE11

Aw it doesnt work for me nice try tho :P
EDIT: I used Google Chrome 42.0.2311.90

It works on Chrome for me

Doesn't work for me, and gives me the option to "Prevent page from displaying additional dialogs".

C++
#include <iostream>
#include <cstddef>

int main() {
    size_t sum = 0;
    for (size_t i = 10; i >= 0; --i) {
         sum += i;
    }
    std::cout << sum << std::endl;
    return 0;
}

 The condition i >=0 is always true because size_t is unsigned.

Nice one, but compilers normally output a warning for this ;)

@Synxis Yes compilers do. But only if you turn on compiler warnings. g++ won't warn you about this without them.

You should always use -Wall --pedantic anyway.

@queueoverflow The warning doesn't show with only those flags. You need -Wsign-compare which can be turned on with -Wextra.

@FDinoff I'm fairly sure clang will tell you even without explicitly using -Wall

One dash on -pedantic. #pedantic

You are not guaranteed to have a definition of size_t in scope after including iostream, much less that it is available at global scope.

@celtschk I added #include <cstddef> is that better?

A bit. cstddef defines size_t in namespace std, and may (but is not required to) also put it into global scope. So you could do any of the following: (1) prefix each size_t with std:: (where it is guaranteed to be found), (2) include stddef.h instead (which is guaranteed to exist and to put size_t in global scope in addition to namespace std), or (3) forget good style and add using namespace std; :-)

bash
(There was a request for no loops or recursion)
#!/bin/bash

# Demo arrays

foo=("Can I have an array?")

echo $foo

echo ${foo[0]}

foo[2] = `yes`

echo $foo

echo ${foo[2]}

 Instead of assigning the string 'yes' to foo[2], this calls the system command yes, which fills up foo[2] with a never ending amount of "yes\n".

Eventually runs bash out of memory and crashes it

Yes, indeed it does.   But a crash was kind of allowed by the question :)

Yes, just an observation :).  Upvoted.

In fact, I reckon that programs in this little comp that actually crash your machine, or some other denial of service, should get bonus marks )

Correction: yes is just a coreutils program. Not a syscall.

Reworded to avoid this technicality all together - I wasn't focused on the nature of yes, rather I was noting that it is not a bash string, it's a call to an utility outside bash accessed via the backtick command substitution.

Does that program have any purpose that can't be fulfilled by hard coding "yes" into your program?

What do you mean by "hard coding 'yes' into your program"?    This program ostensibly (and actually) demonstrates how to use array syntax in bash.   The string "yes" is just hardcoded, ostensibly, as is the string "Can I have an array".   The fact that it's not actually hardcoded is the way this solution to the OP's challenge works.

C
Letter "x" was lost in a file. A program was written to find it:
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
  FILE* fp = fopen("desert_file", "r");
  char letter;
  char missing_letter = argv[1][0];

  int found = 0;
  printf("Searching file for missing letter %c...\n", missing_letter);
  while( (letter = fgetc(fp)) != EOF ) {
    if (letter == missing_letter) found = 1;
  }
  printf("Whole file searched.\n");
  fclose(fp);
  if (found) {
    printf("Hurray, letter lost in the file is finally found!\n");
  } else {
    printf("Haven't found missing letter...\n");
  }
}

It was compiled and to ran and it finally shout:
Hurray, letter lost in the file is finally found!

For many years letters have been rescued this way until the new guy came and optimized the code. He was familiar with datatypes and knew that it's better to use unsigned than signed for non-negative values as it has wider range and gives some protection against overflows. So he changed int into unsigned int. He also knew ascii well enough to know that they always have non-negative value. So he also changed char into unsigned char. He compiled the code and went home proud of the good job he did. The program looked like this:
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
  FILE* fp = fopen("desert_file", "r");
  unsigned char letter;
  unsigned char missing_letter = argv[1][0];

  unsigned int found = 0;
  printf("Searching file for missing letter %c...\n", missing_letter);
  while( (letter = fgetc(fp)) != EOF ) {
    if (letter == missing_letter) found = 1;
  }
  printf("Whole file searched.\n");
  fclose(fp);
  if (found) {
    printf("Hurray, letter lost in the file is finally found!\n");
  } else {
    printf("Haven't found missing letter...\n");
  }
}

He came back to a havoc on the next day. Letter "a" was missing and even though it was supposed to be in the "desert_file" containing "abc" the program was searching for it forever printing out only:
Searching file for missing letter a...

They sacked the guy and rolled back to previous version remembering that one should never optimize datatypes in working code.
But what is the lesson they should have learnt here?

 First of all, if you take a look at the ascii table you'll notice that there is no EOF. That's because EOF is not a character but a special value returned from fgetc(), which can either return character extended to int or -1 denoting end of file.

 As long as we are using signed char everything works well - char equal to 50 is extended by fgetc() into int equal to 50 as well. Then we transform it back to char and still have 50. Same happens for -1 or any other output coming from fgetc().

 But look what happens when we use unsigned char. We start with a char in fgetc() extend it to int and then want to have an unsigned char. The only problem is that we can't preserve -1 in unsigned char. Program is storing it as 255 which no longer equal to EOF.

Caveat

 If you take a look at section 3.1.2.5 Types in copy of ANSI C documentation you'll find out that whether char is signed or not depends solely on implementation. So the guy probably shouldn't be sacked as he found a very tricky bug lurking in the code.
 It could come out when changing the compiler or moving to different architecture. I wonder who would be fired if the bug came out in such a case ;)

PS. Program was built around the bug mentioned in PC Assembly Language by Paul A. Carter

I love that there's a story with the solution.

Haha! I guess it's the only one. Thanks for reading through!

I love you. Feed me with your stories pls :(

This is absolutely brilliant!

Regex
With appropriate input, the following regex can cause most backtracking regex engine to go into backtracking hell:
^\w+(\s*\w+)*$

Simple input such as "Programming Puzzles and Code Golf Stack Exchange - Mozilla Firefox" or "AVerySimpleInputWhichContainsAnInsignificantSentence." (both strings quoted for clarity) is enough to keep most backtracking regex engines running for a long time.

 Since (\s*\w+)* allows for the expansion \w+\w+\w+...\w+, which means the regex engine will basically try out all possible ways to split up a string of word characters. This is the source of the backtracking hell.
  It can easily be fixed by changing \s* to \s+, then (\s+\w+)* can only be expanded to \s+\w+\s+\w+...\s+\w+.

I hate backtracking regex engines.

I tried this with Perl first, but it appears that Perl can notice a loop here. I didn't try AWK, because no regular expression can cause such behavior in AWK. PHP automatically makes regular expression which takes too long to match fail (which is silly, but that's PHP for you - it automatically inserts bugs into programs). However, it actually works in Python.

@xfix: As for why Perl managed to avoid backtracking hell, this article explains the reason. However, it is not enough against the case as shown here (scroll down to performance section). PHP (actually PCRE library) has a backtracking limit, and a proper program should always check for the return value of the function to decide whether the execution was halted, or ran to completion.

This is so SLICK.

JavaScript
function thiswillLoop(){
var mynumber = 40;
while(mynumber == 40){
mynumber = 050;
}
return "test";
}
thiswillLoop();

 050 is an octal constant in Javascript, and it happens to have the decimal value of 40.

I find this obvious. :-)

I didn't know javascript did this. But after reading the code I said: "050 has to be some way of representing 40, probably base 8 or something"

This needs to be hidden better.

It is obvious..

Haskell
head $ reverse $ (repeat '!') ++ "olleH"

Well, think of it! It would be the same as head $ "Hello" ++ (repeat '!'), i.e should just return 'H'.

 In haskell lists are recursive structures, with first element being the topmost. To append to a list, you have to unroll all those elements, place your appendix, and put the lifted elements back. That wouldn't work on an infinite list. Similarly, reversing an infinite list won't magically give you your "Hello" back. It will just hang forever.

Too bad this doesn't actually work :-/

How doesn't it work?

@crazedgremlin when I tested this on Fedora the OS eventually killed the process. (< 5 minutes) because it used up all the memory on the system.

Interesting! I didn't realize that this happened. I don't venture into gobbling-all-memory territory all that often.

That's still a valid solution: it doesn't exit, it runs as long as it can till the system can't support it anymore...

Java under Windows
public class DoesntStop
{
    public static void main(String[]a) throws InterruptedException, IOException
    {
        ProcessBuilder p = new ProcessBuilder("cmd.exe","/c","dir");
        p.directory(new File("C:\\windows\\winsxs"));
        Process P = p.start();
        P.waitFor();
    }
}

 Program relies on a jammed standard output stream from the commandline to get stuck. The WinSXS directory under windows has multiple thousands of files with long names so it is almost guaranteed to clog stdout, and the waitFor can't return so the program is deadlocked

Maybe I'm being dense, but won't this return eventually?  It just might take awhile.  Maybe I don't get what you mean by "clog[ging] stdout".

if the stream is not emptied the program blocks, caused me some headaches already thats why i used it; the long directory only ensures that the buffer runs full

Ah, gotcha.  Nice!  +1

To compare apples and oranges... in C
I'm impressed that there is no piece of code here using a goto... (You know: Goto is evil!)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
    char *oranges = "2";
    long int apples;

next_harvest:

    apples = random() % 3;

    printf("%ld apples comp. %s oranges ...\n", apples, oranges);

    if( apples != (long int)oranges )
    {
        sleep(1);
        goto next_harvest;
    }

    return 0;
}

The sleep is just for being able to read it. Press ^C if you don't have an endless amount of time to wait for something that never happens ;-)

You sneaky bastard, goto is innocent in this :)

is the random() the vodoo used?

@masterX244 No, it isn't. Take a close look at the cast here. What happens when you omit the cast?

ahh, "2" !=2 ; got it

Well "2" probably can't ever be 2, but if you used a bigger number (and a multiple of at least 4), it could happen ;)

@orion: Yes you are right, it could be. And goto is still evil, but bad type castings are even more evil!

@hvd: If you omit the type casting you 'll get a warning from the compiler. Still the behaviour will be the same.

@max.haredoom Yes, I know. That warning was a hint to masterX244 to understand what is happening.

C, with certain optimizing compilers
This program increments an integer variable until it overflows.
#include <stdio.h>
#include <stdint.h>
int main()
{
    int32_t x = 0;
    while(x + 1 > x)
        x++;
    printf("Got overflow!\n");
    return 0;
}

 Signed integer overflow is undefined behaviour. Usually in practice it wraps, when optimizations are turned off. With optimizations on, compilers can and do decide that x + 1 > x is always true.

Perhaps use int32_t; a 64 bit int would take really, really, really long (585 years if each iteration takes a nanosecond).

C++
int main()
{
  int x = 1;
  //why doesn't this code terminate??/
  x = 0;
  while(x) {} //no-op/
  return 0;
}

The weird commenting style is the trick. Hint: trigraphs.

This is a too basic example of an infinite loop.

@Ismael But if x == 0, while (x) {} will never be entered... right?

Sorry, didn't see the x=0;. But looking at the code, won't it terminate right away?

@Ismael Nope; look closely...

From what I see, it's still an infinite loop.

Seems you have fooled a few people. I think I've got it, although I wasn't aware that comments in C worked like that.

??// == /* :)

Those Trigraphs are sooo overused here :(

I almost feel like trigraphs should be put in Standard Loopholes Which Are No Longer Funny.

@TheDoctor: ??/ is a trigraph for a backslash character, so the backslash splices the line where x is assigned 0 to the end of the comment, making it part of the comment.

@undergroundmonorail Posted

Expanding trigraphs in comments is something I'll never understand why.

Java
I particular love this side effect of the autoboxing optimization:
class BoxingFun {
  public static void main( String[] args) {
    Integer max;
    Integer i;

    max = 100;
    for( i = 1; i != max; i++ ) {
      System.out.println("Not endless");
    }
    max = 200;
    for( i = 1; i != max; i++ ) {
      System.out.println("Endless");
    }
  }
}

 Because of autoboxing, Integer objects behave almost like plain ints here, with one exception: The i != max in the for loops compares the references (identity) of the Integer objects, not their value (equality). For values up to 100 this surprisingly "works" nevertheless because of an optimization in the JVM: Java preallocates Integer objects for the "most common values" and reuses them when autoboxing. So for values up to 100 we have identity <==> equality.

Given that some Java guys still consider C++ operator-overloading as evil ...

You don't need the initialization = new Integer(0), as you are initializing the values afterwards anyways. (This might make the reason less obvious.)

@PaŭloEbermann: Good point, I have edited the code.

Ruby/C
#include <stdio.h>
#ifdef llama
def int(*args)
end
def main(arg)
  yield
end
void = nil
#endif
#define do {
#define end }
int main(void) {
  int x = 10;
  while(x-=1) do
    printf("%i\n",x);
  end
    return 0;
}

This works correctly in C, counting down from 9 to 1 in STDOUT. When run in Ruby, it does not terminate, because

 0 is not a false value in Ruby.

Do languages at once...impressive.

JavaScript
// This multiplies the elements in the inner lists and sums the results.
function sum_of_products(var items)
{
        var total = 0;
        for(var i = 0; i < items.length; i++) {
                var subitems = items[i];
                var subtotal = 1;
                for(var i = 0; i < subitems.length; i++) {
                        subtotal *= subitems[i];
                }
                total += subtotal;
        }
        return total;
}

// Should return 1*2 + 3*4*5 + 6*7*8*9 + 10*11 = 3196
sum_of_products([[1, 2], [3, 4, 5], [6, 7, 8, 9], [10, 11]]);

 Both loops use the same loop variable, so depending on the input, the inner loop can keep the outer loop from ever finishing.

What language is this?

@ronondex Javascript

Ah, yes, it's Javascript. I remembered to enable the syntax hilighting but had to forget to put it in the title too :)

I find this obvious. :-)

@rafaelcastrocouto Yeah, it kind of is, but it's also really easy to miss, for example when moving a loop from one function to another or just glancing over code. Also, do note that this actually works correctly in some languages, including C, due to variable shadowing. :)

C
This should print a code table for all ASCII characters, from 0 to 255. A char is large enough to iterate over them.
#include <stdio.h>

int main(){
    char i;
    for(i = 0; i < 256; i++){
        printf("%3d 0x%2x: %c\n", i, i, i);
    }
    return 0;
}

 All chars are less than 256. 255++ gives 0 due to overflow, so the condition i < 256 always hold. Some compilers warn about it, some don't.

To make is seem to do something more useful, maybe use something like printf("%3d %2x: %c", i, i, i); (for a code table) in your loop.

@PaŭloEbermann: Great idea.

I use this trick in my classroom, with printable unsigned characters between 32 and 128. :)

C++
How about the classical C++-programmer's trap?
int main()
{
   bool keepGoing = false;

   do {
       std::cout << "Hello, world!\n";
   } while( keepGoing = true );

   return 0;
}

I don't get this? Is it about using. =instead of == ?

@user689 exactly. keepGoing = true was meant to compare the value of keepGoing, instead it assigns the value to keepGoing; in addition the whole statement keepGoing = true evaluates to true (which is what allows you to write things like a=b=c=d=0) leading to an infinite loop.

This is ever more reason to use yoda conditions.

@RyanEdwardDougherty Haha like that I never heard them being called. For the morning laugh thanks.

@RyanEdwardDougherty: Of course == true (or Yoda-style true ==) is redundant anyway, and the condition should simply read while (keepGoing).

@Ryan No. Big no. This is reason to turn on compiler warnings.

Java:
public class LoopBugThing{
   public static void main(String[] args)
   {
      int i = 0;
      while(i < 10)
      {
         //do stuff here
         i = i++;
      }
      System.out.println("Done!");
   }
}

 The "i = i++" is a pretty common beginner mistake and can be surprisingly hard to find

Python
a = True
m = 0
while a:
    m = m + 1
    print(m)
    if m == 10:
        exit

 it should be exit() and not exit. As I understand it, exit() is the command to exit the python interpreter. In this case the call is to the representation of the function and not to the function see: exit-discussion. Alternatively break would be a better choice.

Could you please explain what exit actually is? It seems to be a class, but what is it used for? You could also change print m to print(m) so that this also works with Python 3.

Those kinds of things... Like when my elseif didn't work because it was elif.

Thanks @moose updated print statement and the spoiler message

Haskell
Some code to time the computation of a given value of the Ackermann
function. For very low values it usually terminates. On my machine
very low values means something like 3 5 or smaller with compiled
code and -O. In ghci low values means something like 3 3.
The ' symbol seems to mess up syntax highlighting, not sure why.
In some places they are needed so can't remove all of them.
Edit- changed language.
{-# LANGUAGE NamedFieldPuns #-}
import Control.Concurrent.STM
import Control.Concurrent
import Data.Time.Clock.POSIX

data D = D { time :: !POSIXTime
           , m :: !Integer
           , n :: !Integer
           , res :: !(Maybe Integer)
           } deriving Show

startvalue = D 0 3 8 Nothing

-- increment time in D. I belive lensen make code like
-- this prettier, but opted out.
inctime t t' (d@D{time}) = d {time = time + t' - t }

-- Counting time
countTime :: TVar D -> POSIXTime -> IO ()
countTime var t = do
    t' <- getPOSIXTime
    atomically $ modifyTVar' var (inctime t t')
    countTime var t'

-- Ackermann function
ack m n
    | m == 0    = n + 1
    | n == 0    = ack (m - 1) 1
    | otherwise = ack (m - 1) (ack m (n - 1))

-- Ackerman function lifted to the D data type and strict
ack' (d@D{m, n}) = let a = ack m n
                   in seq a (d { res = Just a })

-- fork a counting time thread, run the computation
-- and finally print the result.
main = do
    d <- atomically (newTVar startvalue)
    forkIO (getPOSIXTime >>= countTime d)
    atomically $ modifyTVar' d ack'
    (atomically $ readTVar d) >>= print

 This causes a livelock. The counting thread repeatedly causes
 the Ackermann computation to roll back since they touch the
 same TVar.

marking it as lang-hs instead of lang-haskell seems to work better (it's one of the extensions in the google prettifier)

C++
A bit of random ?
class Randomizer
{
   private:
   int max;

   public:
   Randomizer(int m)
   {
      max = m;
      srand(time(NULL));
   }

   int rand()
   {
      return (rand() % max);
   }
};

int main()
{
  Randomizer r(42);
  for (int i = 0; i < 100; i++)
  {
     i += r.rand();
  }
  return (0);
}

 Doesn't call the function rand but instead call recursively the Randomizer::rand function.

Extra parentheses in return statement, yuck.

This will eventually segfault, though.

Java -- No loops or recursion
I just started learning regular expressions and wrote my first program to test if my string matches a regular expression.
Unfortunately, the program does not produce any result.  It holds up the terminal.  Please help in finding the problem.  I have not made any use of loops, there is no recursion involved.  I am completely baffled.
import java.util.regex.*;

public class LearnRegex {
     public static void main(String[] args) {
         Pattern p = Pattern.compile("(x.|x.y?)+");
         String s = new String(new char[343]).replace("\0", "x");
         if (p.matcher(s).matches())
             System.out.println("Match successful!");
     }
}

What have I done wrong?  Why doesn't my program end?  Please help!
Ideone link here.

 This is a stupid example of catastrophic backtracking.  The complexity is O(2n/2).  While the program might not run indefinitely, it'd probably outlive both living and non-living objects around and not-so-around.

C / C++
C++ just allows the easy inline variable declarations used here, but it's just as easy to make this mistake in plain old C...
#include <stdio.h>

int main(void)
{
    int numbers[] = {2, 4, 8};

    /* Cube each item in the numbers array */
    for(int i = 0; i < 3; i++) {
      for(int j = 0; j < 3; i++) {
        numbers[j] *= numbers[j];
      }
    }

    /* Print them out */
    for(int i = 0; i < 3; i++) {
      printf("%d\n", numbers[i]);
    }

    return 0;
}

 In the inner loop, 'j' is compared but never incremented. (The 'i++' should actually be 'j++'). This is not so much a sneaky trick but more of an actual error I've made in the past ;) Something to watch out for.

This usually takes me at least 5 minutes to debug. I hate it when I did this.

C
You should only need one of the two loops, but which one you need depends on your compiler.
main()
{
        int i, a[10];

        i = 0;
        while (i <= 10) {
            i++;
            a[i] = 10 - i;
            printf("i = %d\n", i);
        }

        /* Now do it in reverse */

        i = 10;
        while (i >= 0) {
            i--;
            a[i] = 10 - i;
            printf("i = %d\n", i);
        }

}

 A simple bounds overrun that resets i to a non-terminating value. Compilers can differ on whether they allocate i above or below a on the stack, so I've included overruns in both directions.

C#
The following is a simple class performing an arithmetic operation (summation) on a large input array using a background thread. A sample program is included.
However, even though it is quite straightforward, it never terminates. Note that there is no sleight of hand (character lookalikes, hidden/missing semicolons, trigraphs ;-), etc.)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

class Program
{
    static void Main()
    {
        var summer = new BackgroundSummer(Enumerable.Range(1, 1234567));
        Console.WriteLine(summer.WaitAndGetResult());
    }
}

public class BackgroundSummer
{
    private IEnumerable<int> numbers;
    private long sum;
    private bool finished;

    public BackgroundSummer(IEnumerable<int> numbers)
    {
        this.numbers = numbers;
        new Thread(ComputingThread).Start();
    }

    public long WaitAndGetResult()
    {
        while (!finished) { /* wait until result available */ }
        return sum;
    }

    private void ComputingThread()
    {
        foreach(var num in numbers)
        {
            sum += num;
        }
        finished = true;
    }
}

 This is an example of a real-world nasty bug which might appear in your code as well. Per the .NET memory model and C# specification, a loop such as the one in WaitAndGetResult might never terminate unless you specify the variable as volatile, because it is modified by another thread. See this StackOverflow question for details.
 The bug is dependent on the .NET implementation, so it might or might not affect you. But usually, running a release build on an x64 processor seems to display the problem. (I tried it with “csc.exe /o+ /debug- infinite.cs”.)

Javascript
var а = 0;
a = 1;
while(а<10){
    a++;
}

 The variables used in 1st and 3rd line are different from the ones used in 2nd and 3rd line.
  One uses a (U+0061) while the other uses а (U+0430)

I don't see a problem here. I ran it and it worked fine. What am I missing?

this will most likely work everywhere since the unicode will probably be converted. Got a +1 since it is the most invisible as you can get!

Just to hide it completely (replace á with U+0430) If this was your code, good luck finding the problem: var a;var points = 0;function fiftyfifty() {points++;if (Math.random() > 0.5)return true;}; á = fiftyfifty(); while (a === undefined) {á = fiftyfifty();} console.log("Points: " + points); I would give up, delete this forever, clean my computer, maybe virus scanner just to be sure and rewrite it completely. EDIT: Because var a = 0; a = 1; is not very realistic

Javascript
This once bit me years ago:
function outerloop(){
  for(i=0;i<10;i++){
    innerloop();
  }
}
function innerloop(){
  for(i=0;i<5;i++){
    console.log(i)
  }
}
outerloop();

 The trick here is that when one uses for( i=0 ..., the variable i is created in the global scope (even if they're in separate functions), so it gets overwritten every time by the inner loop. This is an easy pitfall for those coming from C++ or PHP. The fix is to use var to declare the variable in local scope (for (var i...)

PowerShell
$i = 1

do {
    $i++
} until( $i > 10 )

The > is not the greater-than operator (which is -gt); it is the redirection operator. Since nothing is returned, PowerShell evaluates the expression as false and continues.

C
int main(void) {
  float x = 0;
  while(x != 1) x+=0.1;
}

lots of nooses for a C developer....

main should be main()

Also, this terminates perfectly.

@trion, updated answer, should hang now

It will hang on typical implementations, but for completeness: it will run successfully on implementations where FLT_RADIX is 10. A quick search brings up TIGCC as an example of such an implementation.

I imagine you could find another value that would be wonky when FLT_RADIX is 10, like 1.0/3.0.

@DavidConrad Indeed, but that cannot be expressed as a decimal literal. The 0.1 in this answer looks like it's probably an exact number, even though it's probably not. When you have to spell out the division operation, the problem becomes more obvious.

C
This was tested on a 64 bit machine with gcc using the compiler flag -fomit-frame-pointer.
int main() {
    long x = (long)main;
    asm("sub %0,%%rsp"::"i"(sizeof(x)));
}

 This makes the return address the address of main. Which makes an infinite loop. The assembly line is needed to not run out of stack.

Didn't get why it hangs until used -S with gcc. I took %0 as $0 and didn't understand why the asm line wasn't a nop.

It is a GUI program that will show an empty frame titled Hello, world! and hide the frame in 1 second.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class Main {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                // Create a frame titled "Hello, world!".
                final JFrame frame = new JFrame("Hello, world!");
                frame.setVisible(true);

                // After 1 second...
                Timer timer = new Timer(1000, new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        // Hide the frame.
                        frame.setVisible(false);
                    }
                });
                timer.setRepeats(false);
                timer.start();
            }
        });
    }
}

 The frame is hidden, but it is not disposed, so the virtual machine would not terminate. Reference: http://docs.oracle.com/javase/7/docs/api/java/awt/doc-files/AWTThreadIssues.html#Autoshutdown

Anyone who has programmed in Swing enough will know this.

@Quincunx I think your comment can be applied to all answer above.

I agree. However, this answer is obvious to anyone who has barely begun programming in Swing. Swing programmers learn to use frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);, and when that is forgotten, the application just doesn't close. This implies that something special is needed to close the frame, not just setting it as invisible.

Speaking as someone who's never heard of Swing before: Why would anyone who has been programming for more than a few weeks think that making something invisible is the same as releasing it?

@alexis I did, and I sometimes still forget to add setDefaultCloseOperation until I see my program is still running after closure.

Fair enough, @johnchen, sorry if I came on too strong. IMHO Swing would make it easy to accidentally write non-terminating programs, but it's because it has a hidden event loop and you must explicitly arrange for termination instead of just letting your control flow run out as in most languages. Confusing visibility with resource (de)allocation is on another level-- I guess you have to know a little Swing before you can make this mistake.

Java
Spawns a thread that will sleep for 1 second. The program should effectively sleep for a second while waiting for that thread to quit, and then end.
import java.lang.*;

class A {
    static boolean done;
    public static void main(String args[]) {
        done = false;
        new Thread() {
            public void run() {
            try {
                Thread.sleep(1000); // dummy work load
            } catch (Exception e) {
                done = true;
            }
            done = true;
            }
        }.start();
        while (!done);
        System.out.println("bye");
    }
}

Why it doesn't end

nice quirk :P; there are always some of them in each language

Though depending on your VM this might work just as expected.

JavaScript
while(true)
    if(NaN == NaN)
        break;
    else
        console.log("Batman");

 A funny property of the global NaN (Not a Number) object in JavaScript is that it is not equal to itsself. To test if a number is NaN one must use isNaN(). It's also amusing that typeof(NaN) returns "number".

The behaviour is actually part of the IEEE754 spec for floating point behaviour, which is used in many languages (C++, Java, .Net, etc) and is the usual way to represent floating point numbers in binary. Javascript uses dynamic typing, so a variable can contain a numeric value, a string value or an object reference (e.g. an array). A NaN is still a numeric type of value, which is why its type is Number - it's not an empty string or a Null object.

It's kind of funny that the type of NaN is actually number.

C
This prints numbers from 0 to 9. Or at least it should...
#include <stdio.h>

int main() {
    int i;
    char line[12]; // "Iteration: x"

    for(i = 0; i < 10; i++) {
        sprintf(line, "Iteration: %d", i);
        puts(line);
    }

    return 0;
}

 This is a classic off-by-one error triggering a stack overflow. The
 string is indeed 12 characters long, but the programmer forgot about
 the NULL terminator inserted by sprintf! On GCC, local variables are
 pushed to the stack in declaration order. Other compilers may order
 the variables differently. Since the stack grows backwards, this means
 i is after line in memory. The null byte overwrites the least
 significant byte of i. At the end of the block, i is always 0.
 i is incremented and it loops forever with i = 1.

C
int main(void)
{
        float count = 0;
        while(count < 33554432L)
        {
                count++;
        }
        return 0;
}

 Floating-point numbers have limited precision.  Under IEEE 754 floating-point math, a single-precision float only has 24 bits of precision: the largest integer that can be represented exactly is 16,777,216.  16777216 + 1 = 16777216.

Not, in fact, true in either theory or practice. Clause 5.2.4.2.2 of the C standard says that the accuracy of these floating point operations is implementation-defined, and implementations are furthermore allowed to evaluate float arithmetic using double or even long double precision. Clause 5.1.2.3 allows implementations to omit unneeded side-effects. The clang compiler, with optimization turned on, does exactly this. It optimizes away the entire loop and the loop control variable, yielding a program that terminates with return 0. The emitted (x86) machine code is 2 instructions.

Moreover, if the loop doesn't have any side effects (like here where the count variable isn't used), compiler may assume that loop does terminate.

@JdeBP C requires assignments and casts to drop any excess precision, and no matter what precision float has on a particular implementation, there will be some value for which adding 1 has no effect. 5.2.4.2.2p8: "Except for assignment and cast (which remove all extra range and precision), the values of operations with floating operands and values subject to the usual arithmetic conversions and of floating constants are evaluated to a format whose range and precision may be greater than required by the type." Ruslan's comment seems like the only reason it can terminate.

Too many float related answers!

Ruslan's comment is a restatement of what I said, where I explicitly pointed to clause 5.1.2.3. Compilers don't solve the halting problem. They eliminate code with unneeded side effects. Here, they recognize a canonical iteration statement with a non-constant controlling expression and no needed side-effects (nor synchronization operations), and eliminate it. Clause 6.8.5 explains how.

Also: The wording that you italicized and and the wording in clause 6.8.5 are new for the 2011 standard, the latter introduced by Hans Boehm and Lawrence Crowl in 2009 (N1349). Note that, as explained in the Rationale, prior revisions of the language pretty much required that float expressions be evaluated as double, and had no such narrowing requirement upon assignments.

C#
Perhaps too obvious, but
class Program
{
    static void Main()
    {
        int x = 0;
        while (x * x != 1000)
            x++;
        System.Console.WriteLine("Square root of 1000 is " + x);
    }
}

 The square root of 1000 is not an integer, so it will never find it. It's just going to loop forever, assuming overflows aren't checked (the default is unchecked). So like I said, perhaps too obvious. But when I first saw it, I was pretty sure it was going to terminate - 1000 looks as though it should have an integer square root - to me, anyway.

Postscript
hello.ps:
/hello
{
    (Hello, world\n) print
    quit
}
dup 2 3 index cvx put def

hello

This prints "Hello, world" forever.  To try it with ghostscript:
gs -sDEVICE=nullpage hello.ps

 dup 2 3 index cvx put replaces the procedure's call to quit with a recursive call to procedure hello.  Since postscript does tail call optimization, this runs forever without overflowing the stack.

@luserdroog Thanks for the kind words, and for helping me learn this technique.

TeX (Plain): Typesetting The Song That Never Ends
Compile with pdftex. It is not obfuscated (besides, well, being written in TeX) and actually does end, as pdftex stops after somewhat about 2.6 million pages...
\font\bigrm=cmr12 at 14pt
\centerline{\bigrm The Song That Never Ends}
\bigskip
\def\songthatneverend{
\noindent This is the song that never ends.\hfil\break
Yes, it goes on and on my friends.\hfil\break
Some people started singing it not knowing what it was,\hfil\break
and they'll continue singing it forever just because\smallskip

\expandafter\songthatneverend}
\songthatneverend
\bye

Hmm, this is not that underhanded, I would say.

@PaŭloEbermann: No it isn't. It is just TeX :-)

Ruby
if p
  //misses
  raise 'Unreachable'
end

while p //nonsense, Kernel#p always returns nil, which is falsey, so this will immediately terminate.
  puts 'Looping'
end

puts 'Done looping'

Batch
This loops forever outputting Hello.
@echo off
for /l %%a in (0,0,1) do echo Hello.

 The for loop tries to count from 0 to 0 incrementing by 1 - (0,0,1). So it never reaches zero.

Or if you want to cause the prompt to crash.
@echo off
for /l %%a in (0,1,1) do call %%%%a
:1
echo END

--
h:\uprof>end.bat
******  B A T C H   R E C U R S I O N  exceeds STACK limits ******
Recursion Count=477, Stack Usage=90 percent
******       B A T C H   PROCESSING IS   A B O R T E D      ******

C++
#include<fstream.h>
int main()
{
 char ch[80];
 ifstream fin("evil.txt");
 while(fin)
 {
  fin.get(ch,50); //read by lines
  cout<<ch;
 } //nothing wrong, right? wrong.
 return 0;
}

evil.txt contains following data :
hello.
I am awesome.

 fin.get() leaves a '\n' in input stream. The rest is Elementary, my dear.

How about this...
#include<stdio.h>

void main(){
while((10*5/3)!=(10/3*5))
printf("In a loop\n");
}

Mathematically
(10/3)*5==(10*5)/3;

You can omit the parentheses, and even use the same type for both a and b. But it is still quite obvious where the problem is, you should hide it in some piece of program which seems to be useful.

Javascript
Here's a typical beginner's programming exercise.

Continually repeat a sequence of 1..n1, until you've output a total of n2 numbers. For example, looping through 1..3 where the total quantity is 10 would produce this:
1 2 3 1 2 3 1 2 3 1

Below is a solution that uses a currying function. It's simple, elegant, and will hang your browser :-)
function output(msg) {
    $('<span></span>').text(msg).appendTo($('#output'));
}

function loopThroughSequence(max) {
    i = 0;
    return function() {
        if(i >= max) {
            i = 0;
        }
        return ++i;
    }
}

var getNextInSequence = loopThroughSequence(3);
for(var i = 0; i < 10; ++i) {
    output(' ' + getNextInSequence());
}

 Note that loopThroughSequence forgets to declare i in scope. (It needed to preceed 'i' with the 'var' keyword.) Instead, it uses the i value declared below it in the for loop, and continually resets it back to zero.

A function that returns another function ... it ain't that simple. And the double loop "i" has been posted by @Aleksi Torhamo

Whitespace
(actual working code follows)

 Readable version:

 FSSSSSTTFFSFSSSSSTTFF

 Where F is linefeed, S is space and T is tab

The Stack Exchange platform doesn't support Whitespace. You may want to use normalized Whitespace, or paste the script on the platform that does support it.

The code is there when I try to edit but apparently does not render properly. In any case, it is more a positional answer that the OP's question can be (maybe best) answered using Whitespace.

Haskell
This is just a simple program to illustrate return statements. Since the return statement ends the function, it doesn't run anything after it.
sayHello :: IO String
sayHello = do
    return "Hello!"
    sayHello

main = do
    hello <- sayHello
    putStrLn hello

 Return statements don't end functions, unlike in other languages.

C
int main(void) {
  int x;
  while(x<=10) x+=1;
}

from my experience this thing loops indefinitely only after 4 years of stable production at 3AM on a Saturday and once it loops for first time no system reboot can make it go away and within 15 minutes it happens to all high availability servers, dumping the entire production stack offline for a day.

Why the downvote? This is a variation of a real deal, the int usually gets randomly allocated on a zero-padded memory segment, but just sometimes gets allocated where there's garbage already so incrementing never reaches 10

Compilation fails due to missing ().

@bbozo it ought to reach 10 anyway, even if it starts with garbage, due to wraparound.

@IanMallett: Not necessarily. Accessing an uninitialized non-static variable is undefined behavior. So is signed integer overflow.

@Dennis technically true, but practically not.  Every low-level C compiler is going to implement int as a 16- or 32-bit signed data type (and probably the latter) with either ones-complement or twos-complement overflow behavior (and probably the latter).  The OP mentioned nothing about needing a special platform/compiler, so I'm assuming it's a canonical one.

@IanMallett: Why does integer overflow on x86 with GCC cause an infinite loop?

@Dennis: So the compiler can make use of the fact that's it's undefined behavior to optimize.  Thanks!

Java
public class Main {
    public static void main(String[] args) {
        try{
        double i=1.0/0.0;
            while(i==i+1){  //weired condition should never be true
                System.out.println("This should never be printed");
            }
        }catch (ArithmeticException e){
            System.out.println("Caught divide by 0 exception");

        }
    }
}

The classic NaN :D

@SilviuBurcea Not a NaN (NaN != NaN), but an infinity.

This should be hidden better.

Ruby
This is a super efficient piece of code that simulates a dice.
def almost_dice
  rand(7) # will output a number between 0 and 6.
end

#I want a dice that outputs a number between 1 and 6, so I have no other choice, right?
def proper_dice
  d = almost_dice
  while d = 0
    d = almost_dice #Eventually, I'll get d != 0
  end
  return d
end

puts proper_dice

 In ruby what could look like a test : d = 0 is actually an assignment. Since the assignement always succeed, then the test always returns true, hence the infinite loop

Answer: http://i.stack.imgur.com/DDifD.png

Same trick works the same way in C

@GlennRanders-Pehrson no, in C the assignment would have the value 0 (which is falsy), so it wouldn't loop at all.

@PaŭloEbermann  Right, it's the same trick (mistaking "=" for "=="), but not exactly the same, as you said.

C#
Let's take a page from this answer: https://codegolf.stackexchange.com/a/24376/16729 but do the computation on a background thread in the class constructor!
class BackgroundSummer
{
  static int sum;
  static BackgroundSummer()
  {
    // Let's compute the sum on another thread!
    var thread = new System.Threading.Thread(ComputeSum);
    thread.Start();
    thread.Join();
  }

  static void ComputeSum()
  { /* omitted: compute the sum here */ }

  static void Main()
  { }
}

An explanation of why this runs forever is here: http://ericlippert.com/2013/01/31/the-no-lock-deadlock/

Scala
var break = false
for(i <- Stream.from(0) if !break) {
  break = i >= 10
}
println("Well done!")

 Infinite streams will continue to be evaluated even if break is true.

Or the second one.
var g = 6
def counter: Int = {
  g -= 2
  g
}
def test() = {
  val t = ListBuffer('s','t','a','r','t',' ','e','m','p','t','y')
  var i = t mkString // returns "start empty"
  var l = ListBuffer[Int]()
  while(i != "42") i = (l += counter) mkString // returns "42 after two iterations"
  s"$i should equal 42"
}
println(test())

  mkString captures the second argument as a separator, here s"$i should equal 42". So the value of $i is never "42" but goes indefinitely.

wxpython
"Hello World" example that fails to exit.
import sys
import time
import wx
from wx.lib.pubsub import setupkwargs
from wx.lib.pubsub import pub

class LoggerWindow(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, title="Logger")
        self._log = wx.TextCtrl(self, style=wx.TE_MULTILINE)
        pub.subscribe(self.OnLogMessage, "LOG_MESSAGE")

    def OnLogMessage(self, msg):
        self._log.AppendText(msg)

class GUI(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, title="Demo GUI - Hello World")
        self._logger = LoggerWindow()
        pub.sendMessage("LOG_MESSAGE", msg="GUI Starting")

        # Set up the Hello World message
        self._display = wx.TextCtrl(self, -1, size=(400,20), style=wx.TE_MULTILINE)
        self._display.AppendText("Hello World!")

        # Show it for a while
        self.Show()
        time.sleep(10)

        # Done
        self.Destroy()

App = wx.App()
Gui = GUI()
App.MainLoop()

 The log window, while not showing, keeps existing, so the "GUI" window disappears but the app keeps running.   I had intended for this to be another example of "not using a loop", but obviously I am using a loop!

Python
def sum(first, add=[]):
    add.append(first)
    sum = 0
    for el in add:
        sum+= el
    print sum
    return add

if __name__ == '__main__':
    #init
    add = sum(1)
    for el in add:
        sum(el)

this will loop forever due to the fact that expressions in default arguments are calculated when the function is defined, not when it’s called. So the list will grow until the user terminate the script.

JAVASCRIPT
found this while doing my project
function weirdCode(){
  var myarray= ["test",123,false];
  var myarray2 = myarray;
  myarray2[2] = !myarray2[2];
  while(myarray.toString() == myarray2.toString()){
    console.log("shouldn't myarray[2] == false? but it is "+myarray[2]+". but i only edit myarray2, which is "+myarray2[2]);
  }
  console.log("this will never called");
}
weirdCode();

at line "var myarray2 = myarray;" it should be "var myarray2 = myarray.slice()", cause it will be referring the var to myarray, like sharing a var

Another obvious one ... myarray2 = myarray makes it ease to see.

on some coding language, copying an array are 'var CopyOfAnArray = OriginalArray;'

well .. not in js!

JAVASCRIPT
 var x = 1; while(x != 0) x -= 0.1;

 x = 1;
 x - 0.1 = 0.9;
 x - 0.1 = 0.8;
 x - 0.1 = 0.7000000000000001
WHAT!!!!!

Now more about it

Almost literally this answer http://codegolf.stackexchange.com/a/24386/16874

I usually only read JS answers ... you are 100% right, it's the same ... just different languages.

Java, equal but not?
import java.util.HashMap;
import java.util.Map;

public class Endless {
    static class A {
        public A(int a) {
            b = a;
        }

        int b;
        @Override
        public boolean equals(Object obj) {
            return obj != null && (obj instanceof A) && ((A)obj).b == b;
        }
    }

    public static void main(String args[]) {
        Map<A,String> map = new HashMap<A, String>();
        A a = new A(1);
        A sameA = new A(1);

        System.out.println("a is sameA?" + a.equals( sameA ));

        map.put(a, "look ma, no hands!");

        while (!map.containsKey(sameA)){
            //we never get here, do we?
        }
        System.out.println("Done!");
    }
}

While it is not obvious why the loop condition is true, it is quite clear that the problem must be there. I recommend hiding it better in a program piece which seems to do something useful.

How about a fork bomb?
:(){ :|: &};:

The ubiquitousness of the fork bomb makes this rather obviously non-terminating.

Java
public class Looper {
    public static final int END = Integer.MAX_VALUE;
    public static final int START = END - 100;

    public static void main(String[] args) {
        int count = 0;
        for (int i = START; i <= END; i++)
            count++;
        System.out.println(count);
    }
}

This program was blatantly copied from Bloch and Gafter's Java Puzzlers.

The expression i <= Integer.MAX_VALUE is a tautology, at least if i is an int. By definition, no integer can be greater than Integer.MAX_VALUE.

Tcl
set i 1
while $i<=10 {
    puts $i
    incr i
}

 I forgot to brace my expression, so $i will only be substituted once, when while is called

Also, no increment?

Ohh, forgot the increment. Added.

C
This one works..
#include<stdio.h>

void main(){
double a=10;
float b=10;
while(a/3!=b/3)
printf("Infinite loop");
}

Can you add the language?

And similar things have been done already pertaining to floating point precision.

In Ruby:
x = "a"

while ! x.equal?("aaaaaaaa")
   x += "a"
end

 In Ruby, the .equal? method checks for object equality, not value equlity. "aaaaaaaa" is a unique object, and thus has a different object ID than x. Because of this the statement will never be true.

Another one:
a = b = "a"

while a == b
    b << "a"
end

 Here a and b gets the reference to the same object. The << method actually changes the value at the location where the object is referencing, and does not create a new object as most other methods does. Since both a and b references the same location, the values will always be the same.

Powershell
I feel like counting from one to a hundred. Don't you?
$i = 1;
for($i -lt 100;$i++){$i}

...Wait a minute, that's way more than a hundred printing out...
...
...
This should be fairly simple to figure out, and I found it amusing, at least.

C
#include <stdio.h>

int count_bits(unsigned int field)
    {
    unsigned int a = 1;
    int count = 0;

    while (1)
        {
        switch (a)
            {
            case 1 << 31: /* MAX_UINT32 */
                {
                break;
                }
            default:
                {
                if (field & a) count++;
                a <<= 1;
                }
            }
        };
    return count;
    }

int main(int argc, char *argv[])
    {
    printf("%d\n", count_bits(0xdeadbeef));
    return 0;
    }

In C and C++ case is a jump target. The break breaks the switch, but not the while. Substituting break; with return count; will work.

Lua
Totaly boring, but I thought it was still interesting:
-- Example of stack overflow using recursion
-- Function foo: this function will call itself forever: foo(foo(foo(foo(foo...
function foo() -- Our recursive function
    return foo() -- Our recursive call, this will cause the stack to overflow
end
pcall(foo) -- pcall will call foo in protected mode, catching stack overflows.
print("Stackoverflow! Avoid infinite recursion!") -- Use infinite recursion wisely

How does it work?
I dont have a clue. I think its optimized to something like:
call main
exit
label foo:
jmp foo
label main:
push foo
call pcall
push "Stackoverflow! Avoid infinite recursion!"
call print

Notes:

This is not assembly or lua bytecode or anthing
Exponential recursion will result in a stack overflow: foo(foo()). I think this is because this will call foo before it will jmp foo?
Can someone please make a C function and try it out with that? I would love to know if it will result in a overflow or not. (I am guessing it will, but you never know...)

C++'s rules can be pesky some times
a.cpp:
#include "Shape.h" // includes class Shape, with virtual functions on it

int callback(int value, Shape* s)
{
    // aggregates areas
    return value + s->getArea();
}

// Some boring work... we don't even call this function
int aggrigateAreas(Shape* begin, Shape* end)
{
    int rval = 0;
    for (Shape* iter = begin; iter != end; iter++)
        rval = callback(rval, iter);
    return rval;
}

b.cpp:
#include "Shape.h"

int callback(Shape* s)
{
    // aggrigate perimieters
    return s->getPerimiter();
}

// doSomethingImportant will actually do something for us
int doSomethingImportant(Shape* s)
{
    return callback(s); // this was more complicated in real life
}

main.cpp
#include "Shape.h"
#include <iostream>
int doSomethingImportant(Shape* s);

int main() {
    Square s(1); // square with side length 1
    std::cout << doSomethingImportant(&s); // should print 4, right?
    return 0;
}

Sadly, C/C++ is rather unfriendly if you have two functions in different translation units with different names.  They call it a ODR violation (One Definition Rule) and it's Undefined Behavior.  As it so happens, if the linker is not being kind to you today, your call to callback in doSomethingImportant can end up calling the callback in a.cpp.  This is bad enough, but they also don't have the same signatures.  s may get some garbage value, such as something which causes the virtual function lookup of getArea() to return the address just before main, creating an infinite loop when called.  It even gets a few broken opcodes just right to maladjust the stack back to its initials stack height, so you don't even get a sane stack overflow.
Is this against the rules of code golf?  Maybe.  I am trying to claim a win by getting very unlucky with a compiler's handling of undefined behavior.  Technically that's outside of the spec of the language.
However, the scars I put into my cubicle walls that day, dug deep with my fingers as I screamed in agony remain.  Dug over the course of that whole 12 hour work day, with the debugger taunting me as I went (You're {bleep}ing kidding me!  Why did the debugger put me back in a.cpp again!  I commented out all calls to that file wholesale!  Maybe I should recompile the world again)... that has to qualify as "underhanded" somehow, right?  Please?
I will not forget to open the anonymous namespace to store my callbacks
I will not forget to open the anonymous namespace to store my callbacks
I will not forget to open the anonymous namespace to store my callbacks

Java, with OpenCV
(just a snippet)
VideoCapture camera = new VideoCapture(0);
Mat frame = new Mat();
while(frame.get(1, 1)[0]<200)camera.read(frame);

Java OpenCV stores pixel values from 0 to 1, not 0 to 255.

c++
A simple program, to show how operator overloading works:
EDIT: this is inspired by BF
#include <iostream>
class ops
{
public:
    int val=1;
    ops operator * (ops rhs){val++; return *this;}
    ops operator & (ops rhs){val-=3; return *this;}
};
int main() {
    ops a;
    while (a.val>0)
    {
        a=a**&a; //call operator* twice and operator& once, net effect of subtracting 1
        std::cout<<a.val;
    }
    return 0;
}

 This calls operator* once and operator& zero times. *&a is the same as a, because of pointers.

c#
    public void MemoryEfficientCountTo256()
    {
        for (byte i = 0; i <= 255; i++)
        {
            Console.WriteLine(i);
        }
    }

This is from a stackoverflow question. A byte can never be 256, so
 adding one takes it back to 0

C#
   for (; ; )
    {
        try
        {
            string text = "SomeText";
            System.IO.File.WriteAllText(@"c:\Pathwith?.txt", text);

            break;
        }
        catch { }
    }

Well of course it doesn't terminate... why would it?

Isn't this the purpose of the assignment? It should have ended if the file existed but it will throw exception and will never end

It is, it's just not very surprising because it very obviously references a very particular file that most likely doesn't exist.

Now is it better?

Please be sure to include a language header with your answers, e.g. ## Java or ## C.  Welcome to the site!

C++ - Lame
Yay I is pro C++ I learnt for loop real quik now lets make cool program that print 1 to 10 cuz I am awesome and totaly did not chose C++ just cuz C doesnt allow for loop.
#include <stdio.h> // 2 lazy 4 std::cout

int main()
{
    int i = 1;
    for (i < 10; i++;)
    {
        printf("%d\n", i);
    }
}

No why I is pro C++ why U dont work I learn for syntax well :(
upvote @fuandon instead, he gave me the idea. This is my second one anyway...

Clever trick. You might want to explain how it works in a spoiler.

authors: n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳

authors: Тимофей Черников

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