text:
Comparing two numbers
Challenge
Given two integers A and B as input, you must write a program which outputs if A>B, A==B or AB output
A is greater than B

If A==B output
A is equal to B

If A<B output
A is less than B

Where you replace A and B for their integer values.
For example:
 A   B   Output
--  --   ------
 0   1   0 is less than 1
 5   2   5 is greater than 2
20  20   20 is equal to 20

Winning
The shortest program in bytes wins.
Leaderboard

var QUESTION_ID=55693,OVERRIDE_USER=8478;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

Today on Programming Puzzles & Code Golf: ternary statements!

Can functions simply return the solution instead of printing out the solution?

@TheNumberOne No, they must print the solution

CJam, 47
q~_~-g"is
equal greater less
to than"N/Sf/f=*S*

Try it online
Explanation:
q~     read and evaluate the input (array of 2 numbers)
_      duplicate the array
~-     dump one array on the stack and subtract the numbers
g      get signum (-1 for <, 0 for ==, 1 for >)
"…"    push that string
N/     split into lines
Sf/    split each line by space
f=     get the corresponding word (for the signum) from each line
*      join the array of 2 numbers by the array of words
        it effectively inserts the words between the numbers
S*     join everything with spaces

Looks like CJam is one byte shorter than Pyth today :(

According to Defaults for reading several pieces of input, you can read the input as [A B] and eliminate the ] from your code.

@Dennis thanks, I had thought about it but wasn't sure.

@orlp 2 bytes now, and that's a reason to smile, not to frown :)

Appropriate that your code actually contains a smiley in the form of ~_~...

Python 2, 95 94 76 bytes
Input must be comma separated.
A,B=input();print A,'is',['equal to','greater than','less than'][cmp(A,B)],B

I'm intrigued, can you explain what cmp(A,B) is and does? :)

@BetaDecay, https://docs.python.org/2/library/functions.html#cmp. "Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x < y, zero if x == y and strictly positive if x > y.". In cPython 2.7.6, those integers' values are -1, 0, 1 respectively. The function's definition doesn't dictate this, so a pedant might insist that the exact implementation and version of python were given here rather than just "Python 2", but I expect most implementations will behave the same here.

I just want you to know that I didn't copy your answer to come up with mine. I just now saw how close they were. When I wrote mine I was having trouble running the snippet and I could've sworn there wasn't already a Python answer (must've missed the 2nd page). I wrote it completely independently, strangely enough.

@Sp3000 I checked it ,and it works perfectly fine in Python 2.7.6

@ML My comment was referring to a past revision but since it's now outdated I've deleted the comment

I believe you can substitute cmp(a,b) for (a>b)-(a<b) in order to translate to Python 3, but of course that's longer. See my translation attempt.

Labyrinth, 180 152 149 bytes
<
?01.23.511.501.23};,!:?
:
= ;3.114.101.97.116.101.114.32.116.104.97.110.32.{!@
-""
; ;8.101.115:..""""""""""""^
1
.113.117.97.108.32.116.111.32.{!@

Edit: Managed to shave off 3 bytes by reusing 10 between 101, 103 and 108 (the character codes of e, g and l). The explanation below does not reflect this, but it's not a substantial change.
Explanation
There isn't much we can do in the way of saving bytes for printing the strings, that's just going to be long linear sections. So the main challenge in golfing is to avoid large amounts of unnecessary whitespace. That means we want the linear parts to "radiate out" from the left-most column. We can also gain some more savings by reusing the code that prints than B. So let's look at the control flow here:
The program starts on a grid rotation command <. This shifts the current row cyclically to the left with the IP on it, so we get this:
                                                     <
?.23.511.501.23};,!:?
:
= ;103.114.101.97.116.101.114.32.116.104.97.110.32.{!@
-""
1 ;108.101.115:..""""""""""""^
0
1.113.117.97.108.32.116.111.32.{!@

Now the IP is on an isolated cell, so it executes the same command again and again while the < travels further to the left until...
                    <
?.23.511.501.23};,!:?
:
= ;103.114.101.97.116.101.114.32.116.104.97.110.32.{!@
-""
1 ;108.101.115:..""""""""""""^
0
1.113.117.97.108.32.116.111.32.{!@

At this point, the IP has somewhere to go and executes the first linear section (the second row) from right to left. What it does is read A, copy, print. Consume the delimiting character between the numbers, print is (and spaces). Then read B, copy it and subtract A from it at the -.
At this point we hit first "fork in the road". If the difference yielded 0, the IP keeps moving straight ahead towards the bottom branch. That branch simply prints equal to and then B.
Otherwise, the IP takes a left towards the two no-ops "". Then there's another fork. If the difference was negative, the IP takes another left towards the long upper branch. That branch simply prints greater than and then B.
If the difference was positive, the IP takes a right onto the lower branch, which prints less. Now we want to reuse the than from the other branch. But at the same time we don't want to connect the two branches later on, because we'd need a whole bunch of unnecessary spaces. Instead we use a few no-ops to align the lower branch with where the than begins on the upper branch and then start manipulating the source again with ^:
                    <
?.23.511.501.23};,!:?
:                            .
= ;103.114.101.97.116.101.114 32.116.104.97.110.32.{!@
-""                          ^
1 ;108.101.115:..""""""""""""
0                            2
1.113.117.97.108.32.116.111.3 .{!@

Again, this is isolates the IP, so ^ is executed again and we get
                    <
?.23.511.501.23};,!:?        .
:
= ;103.114.101.97.116.101.114^32.116.104.97.110.32.{!@
-""
1 ;108.101.115:..""""""""""""2
0
1.113.117.97.108.32.116.111.3 .{!@

Now the IP can continue moving to the right and print than and B as required.

JavaScript (ES6), 66 bytes
(a,b)=>a+` is ${a<b?"less than":a>b?"greater than":"equal to"} `+b

Defines an anonymous function.
Test by adding f= before it, and call it like alert(f(4, 5))

No savings to be had from the repetitive "than", unfortunately.

Are you sure? The Java answer seems to get around the than ;)

@BetaDecay well, no. Even the Java answer would be the same length repeating the than. public void c(int a,int b){System.out.print(a+" is "+(a==b?"equal to ":a>b?"greater than ":"smaller than ")+b);}

@BetaDecay Is this a valid answer if it doesn't actually output the text? Alternatively 7 for alert() should be added to the score.

@curiousdannii Oh I see, yes this is invalid if you don't count alert() as part of your code and byte count

@BetaDecay oh, I didn't realize that the answer was expected to be printed instead of just returned. If assuming a REPL environment is ok, this could be run in the FireFox console at no cost, otherwise I guess it's up to 73.

Java, 114 113 Bytes or 74 72 67 if we used lambda notation
Thanks to Kevin Cruijssen for currying based solution:
a->b->a+" is "+(a==b?"equal to ":(a>b?"greater":"less")+" than ")+b
Old pre lambda solution
public void c(int a,int b){System.out.print(a+" is "+(a==b?"equal to ":(a>b?"greater":"less")+" than ")+b);}

as user h.j.k meantion in comment, if we used lambda we can do significantly down to 74 bytes.
(a,b)->a+" is "+(a==b?"equal to ":(a>b?"greater":"less")+" than ")+b;

Clever way of compressing than :)

You can remove public if you want to. I would suggest making this into a lambda. You can remove the one space before the {.

And while you're at it, add a comma after #Java so you can be on the leaderboard. ;)

Lambda: (a, b)->a+" is "+(a==b?"equal to ":(a>b?"greater":"smaller" )+" than ")+b; (74 bytes?)

A JAVA ANSWER JUST BEAT A PYTHON ANSWER! THE DAY HAS COME FRIENDS :D. (74 bytes vs 76 from the currently accepted answer).

@AnubianNoob actually it is 72 not 74

The official question spec is to say "less", not "smaller". You might as well do that and lose three bytes! I don't know Java, but will the lambda code print the text or just return it? If it doesn't print it then it's probably not a valid answer.

Would this work: String c(int a,int b){return a+" is "+(a==b?"equal to ":(a>b?"greater":"less")+" than ")+b;} and (a,b)->a+" is "+(a==b?"equal to ":(a>b?"greater":"less")+" than ")+b;

@h.j.k. Shorter lambda using currying: a->b->a+" is "+(a==b?"equal to ":(a>b?"greater":"smaller" )+" than ")+b Yes, I'm aware it has been almost two years. ;) And you can indeed use less instead of smaller based on the challenge description, as mentioned by the two comments above me. Try it here to see how currying is done.

Julia, 69 66 bytes
f(A,B)="$A is $(A>B?"greater than":A<B?"less than":"equal to") $B"

This uses string interpolation to embed A, B, and the ternary inside a single string.
Saved 3 bytes thanks to Glen O.

R, 80 bytes
function(A,B)cat(A,"is",c("less than","equal to","greater than")[2+sign(A-B)],B)

You can save 3 bytes by changing "smaller than" to "less than" to follow the spec above.
+1 for not using a ternary operator.

ah thanks, I did not catch that! fixed!

@bmarks R doesn't have a ternary operator. :P

@AlexA. I know. I meant that using a list and the sign function was very different from the other answers so far (most of which used ternary operators or similar).

Right. For comparison, my first attempt using if/else was 83: function(A,B)cat(A,"is",if(A==B)"equal to"else c(if(A>B)"greater"else"less","than"),B).

Pyth, 52 49 bytes
jdm@cd)._-FQcj"
is
equal greater less
to than
"Qb

Perl, 64 63 bytes
#!/usr/bin/perl -p
s/ /" is ".("equal to ",greaterx,lessx)[$`<=>$']/e;s/x/ than /

62 bytes + 1 byte for -p. Takes input from STDIN, with the two numbers separated by a single space:
$ echo 1 2 | ./cmp
1 is less than 2
$ echo 42 -17 | ./cmp
42 is greater than -17
$ echo 123456789 123456789 | ./cmp
123456789 is equal to 123456789

How it works:
The <=> operator returns -1, 0, or 1 depending on whether the first operand is less than, equal to, or greater than the second. Conveniently, Perl allows negative subscripts with arrays and slices, where the last element is at position -1, the second-to-last element is at position -2, and so on.
In the code
("equal to ",greaterx,lessx)[$`<=>$']

we use the return value of <=> as the subscript in a list slice to get the corresponding string, where $` is the first number and $' is the second.
To avoid repeating than, x is used as a placeholder and replaced in a second substitution at the end.

Alternative solution, 63 bytes
#!/usr/bin/perl -p
@a=(equal,greater,than,to,less);s/ / is @a[$i=$`<=>$',!$i+2] /

62 bytes + 1 byte for -p. Takes space-separated input from STDIN just like the first solution.
How it works:
This solution also uses a slice, but takes advantage of the fact that unlike list slices, array slices can be interpolated into strings (and the RHS of substitutions). This lets us drop the /e modifier and the quotes in the substitution operator.
The real trick is in the slice subscript:
@a[$i=$`<=>$',!$i+2]

For the different values of <=>, this gives:
$i  !$i+2  $a[$i]  $a[!$i+2]
----------------------------
-1    2     less      than
 0    3     equal     to
 1    2     greater   than

When an array or array slice is interpolated into a string, the elements are automatically joined by $" (by default, a single space).

Mouse, 79 bytes
?A:?B:A.!" is "A.B.<["less than"]A.B.>["greater than"]A.B.=["equal to"]" "B.!$

When strings are encountered they're immediately written to STDOUT rather than being put on the stack. The stack can contain only integers.
Ungolfed:
? A:                            ~ Read an integer A from STDIN
? B:                            ~ Read an integer B from STDIN
A. !                            ~ Write A to STDOUT
" is "
A. B. < [ "less than" ]         ~ If A  [ "greater than" ]      ~ If A > B
A. B. = [ "equal to" ]          ~ If A == B
" "
B. !                            ~ Write B to STDOUT
$                               ~ End of program

MATLAB, 105 bytes
x=input('');y=input('');t={'less than','greater than','equal to'};
sprintf('%i is %s %i',x,t{(x>=y)+(x==y)+1},y)

Added a line break before sprintf, to ease readability. It works both with and without this line break, so it's not included in the byte count. Must hit enter between the two input numbers.

Very clever use of sprintf!

GolfScript, 61 bytes
\.@.@="equal to "{.@.@>"greater""less"if" than "+}if" is "\+@

Expects 2 integers on the stack. Try it online.
How it works:

\.@.@ - A and B are already on the stack, and this code piece makes the stack look like this: ABBA. \ swaps the two top items on the stack, . duplicates the top item, and @ rotates the 3 top items (1 2 3 -> 2 3 1).
Then, three items are pushed to the stack: the = sign, "equal to ", and the block between {}. The if statement does this: if the first argument evaluates to true, it executes the first code block (the second argument), otherwise, the second code block (the third argument). So if A and B are equal, it will push "equal to " on the stack. If they are not equal, it will execute the code between the block. Note that = pops the two top items from the stack, so now the stack looks like AB.
Inside the block, you first see .@.@. Before these commands, the stack looks like AB, and after, the stack looks like BAAB. The commands are similar as the ones mentioned above.
Then, there's another if statement. This time, it checks whether A > B, and if true, it pushes "greater" on the stack. Else, it pushes "less" on the stack. After pushing one of these two, it will push " than " on the stack and concatenate it with the previous pushed string. > also pops the two top items of the stack, so now the stack looks like BA"string".
The next three commands are: " is "\+. " is " pushes that string on the stack (stack looks like BA"string"" is "), \ swaps the two top items (stack looks like BA" is ""string"), and + concatenates the two top items (stack looks like BA" is string").
The last command, @, rotates the three stack items, so the stack now looks like: A" is string"B. GolfScript automatically prints the stack values on STDOUT once the program terminates, so then you get the desired output.

Bash, 76
a=(less\ than equal\ to greater\ than)
echo $1 is ${a[($1>$2)-($1<$2)+1]} $2

Fortran, 129
Fortran arithmetic if is perfect for this challenge
Test: ideone
read(*,*)i,j
if(i-j)1,2,3
1 print*,i," is less than",j
stop
2 print*,j," is equal to",j
stop
3 print*,i," is greater than",j
end

Fourier, 147 74 bytes
Non-competing because string printing is newer than this challenge
I~AoI~B` is `<A{1}{`greater than`}A<B{1}{`less than`}A{B}{`equal to`}` `Bo

Try it on FourIDE!
Dunno why I didn't allow printing before... It makes the code readable and is great for golfing

You should be able to save by assigning common letters like 101 and 116 to variables, right? I'm not sure how/if variable scope is handled.

@Geobits There are no local scopes in Fourier, so yeah, I'll work on that

@Geobits Golfed it a bit more using variables

Bash, 94 86 bytes (saved eight bytes thanks to Digital Trauma)
p=equal;q=than;(($1>$2))&&p=greater&&[ ]||(($1<$2))&&p=less||q=to;echo $1 is $p $q $2

Test (on Linux):
echo 'p=equal;q=than;(($1>$2))&&p=greater&&[ ]||(($1<$2))&&p=less||q=to;echo $1 is $p $q $2' > cmp.sh
chmod +x cmp.sh
./cmp.sh 10 12
10 is less than 12

The use of [ ] after p=greater is to prevent || operator from being evaluated before = in the expression ...&&p=greater||(($1<$2))...  (the operator precedence!).
The alternative would be using brackets around (($1>$2))&&p=greater and (($1<$2))&&p=less , but brackets make inner scope for variables, so p would be left unaltered.

p=equal;q=than;(($1>$2))&&p=greater&&[ ]||(($1<$2))&&p=less||q=to;echo $1 is $p $q $2

Lua, 118 bytes
I don't see enough Lua answers here so...
function f(a,b)print(a>b and a.." is greater than "..b or a==b and a.." is equal to "..b or a.." is less than "..b)end

Ungolfed:
function f(a,b)
    print(a>b and a.." is greater than "..b or a==b and a.." is equal to "..b or a.." is less than "..b)
end

Welcome to PPCG!

IA-32 machine code + linux, 107 bytes
Hexdump of the code:
60 89 e5 89 d0 e8 51 00 00 00 4c c6 04 24 20 38
d1 74 20 68 74 68 61 6e 4c c6 04 24 20 72 0d 68
61 74 65 72 68 20 67 72 65 44 eb 11 68 6c 65 73
73 eb 0a 68 6c 20 74 6f 68 65 71 75 61 68 20 69
73 20 88 c8 e8 12 00 00 00 89 ea 29 e2 89 e1 31
db 43 8d 43 03 cd 80 89 ec 61 c3 5b d4 0a 4c 04
30 88 04 24 c1 e8 08 75 f3 ff e3

Because of hardware limitations, the code works with numbers in the range 0...255.
Source code (can be assembled with gcc):
    .globl print_it
    .text
    .align 16
print_it:
    pushal;
    mov %esp, %ebp; // save esp (stack pointer)
    mov %edx, %eax; // put second number in al
    call prepend;   // convert al to string

    dec %esp;       // write ...
    movb $' ', (%esp); // ... a space
    cmp %dl, %cl;   // compare the numbers
    je equal;       // if equal, goto there

    push $0x6e616874; // write "than"
    dec %esp;       // write ...
    movb $' ', (%esp); // ... a space
    jb less;        // if below, goto there

greater:
    push $0x72657461; // write "ater"
    push $0x65726720; // write " gre"
    inc %esp;         // remove a space
    jmp finish;     // bypass the code for "less than"

less:
    push $0x7373656c; // write "less"
    jmp finish;     // bypass the code for "equal"

equal:
    push $0x6f74206c; // write "l to"
    push $0x61757165; // write "equa"

finish:
    push $0x20736920; // write " is "

    mov %cl, %al;   // put first number in al
    call prepend;   // convert al to string

    mov %ebp, %edx; // calculate the length ...
    sub %esp, %edx; // ... of the output message
    mov %esp, %ecx; // address of the message
    xor %ebx, %ebx; // set ebx to ...
    inc %ebx;       // ... 1 (i.e. stdout)
    lea 3(%ebx), %eax; // set eax=4 (syscall "write")
    int $0x80;      // do the system call
    mov %ebp, %esp; // restore the stack pointer
    popal;          // restore other registers
    ret;            // return

prepend:            // writes al converted to string
    pop %ebx;       // remove return address from the stack
appendloop:
    aam;            // calculate a digit in al, rest in ah
    dec %esp;
    add $'0', %al;  // convert the digit to ASCII
    mov %al, (%esp);// write the digit
    shr $8, %eax;   // replace al by ah; check if zero
    jnz appendloop; // nonzero? repeat
    jmp *%ebx;      // return

This is some serious abuse of the stack! The code builds the output message on the stack, from the end to the beginning. To write 4 bytes, it uses a single push instruction. To write 1 byte, it uses two instructions:
dec %esp
mov %al, (%esp);

By luck, most of the fragments to write are 4 bytes. One of them ("gre" in "greater") is 3 bytes; it's handled by pushing 4 bytes and removing one afterwards:
inc %esp

The routine that writes numbers in decimal form uses the aam instruction to divide ax by 10 repeatedly. It's advantageous that it calculates the digits from right to left!

Since there are two numbers to write, the code uses a subroutine, which is called twice. However, because the subroutine writes the results on the stack, it uses a register to hold the return address.

C code that calls the machine code above:
include <stdio.h>

void print_it(int, int) __attribute__((fastcall));

int main()
{
    print_it(90, 102);
    puts("");
    print_it(78, 0);
    puts("");
    print_it(222, 222);
    puts("");
    return 0;
}

Output:
90 is less than 102
78 is greater than 0
222 is equal to 222

ShortScript, 98 bytes
←Α
←Β
↑Γαis
↔α>β→γgreater thanβ
↔α<β→γless thanβ
↔α|β→γequal toβ

C, 155 136 127 83 bytes
f(a,b){printf("%d is %s %d\n",a,a>b?"greater than":a<b?"less than":"equal to",b);}

You can make this much shorter - rename argc and argv, define both a and b in one line, skip the argc check, and more.

Note that the requirement is either a complete program or a function. A function would be much shorter.

@ugoren I was not sure whether it could be a function, so I decided to write a complete program. I'm gonna refactor it. Thank you again!

C# 6, 113 103 100 95 bytes
void C(int a,int b){System.Console.Write($"{a} is {a-b:greater than;less than;equal to} {b}");}

Thanks to edc65 for saving 13 bytes and to cell001uk for saving 5 bytes using C# 6's interpolated strings!

Save 10 bytes void C(int a,int b){System.Console.Write("A is {0} B",a==b?"equal to":a>b?"greater than":"less than");}

@edc65 Nice, thanks!

I love C# formatting: Write("{0} is {1:greater than;less than;equal to} {2}",a,a-b,b)

@edc65 Woah, that's awesome! Thanks! Also thanks for reminding me that A and B have to be replaced by their values, I totally overlooked that >_>

@edc65 I can't find the documentation for that kind of format string.. could you shed some light?

@rob https://msdn.microsoft.com/it-it/library/0c899ak8%28v=vs.110%29.aspx#SectionSeparator

JavaScript, 151 104 100 95 92 bytes
a+=prompt()
b+=prompt()
alert(a+" is "+(a>b?"greater than ":a<b?"lesser than ":"equal to ")+b)

I managed to shorten with help of edc65

I am a JavaScript newbie...

May I ask what you are using to find your score?

Not it's broken (syntax error). Just try before posting

Is there an error now?

Welcome to PPCG! It's a competition for shortest code, so you don't need to follow the best practices, but your code have to be correct. Now, it's not because there is (still) a missing ?. On the other hand, var  is not needed.

This could be a=+prompt(),b=+prompt();alert(a+(a>b?" is greater than ":a<b?" is lesser than ":" is equal to ")+b) 99 bytes

You can write a function and use ES6 to remove some bytes for input.

@jimmy23013 Isn't just going to make it the same as the pre-existing ES6 answer?

@BetaDecay Well, yes... But two prompt()s are so long...

Will it be ok if the brackets surrounding the if-statement were taken out?

No. But go the console panel of your browser (press F12) and try yourself.

If I take out the tildas (~) in your answer, please do not put them back in.

@edc65 you suggested that I have a+=prompt() instead of var a = prompt(). But how does that work, how can a get a value if it was not initialised?

No I suggested a = +prompt(). prompt() return a string, the + convert to a number. You have to compare numbers, not strings: the string "9" is greater than the string "123", while the number 9 is less than the number 123

@edc65 but how does aget initialised

a = expression. That is an initialisation. var a is declaring the variable a. You have to use it in real code for a lot of good reasons. But it's optional in javascript and avoiding var  you save 4 charactes

Rust, 271 bytes
use std::cmp::Ordering::*;fn main(){let v:Vec<String>=std::env::args().collect();let a:u8=v[1].parse().unwrap();let b:u8=v[2].parse().unwrap();print!("{} is ",a);print!("{}", match a.cmp(&b) {Less=>"less than",Equal=>"equal to",Greater=>"greater than"});print!(" {}",b);}

Pretty printed version:
use std::cmp::Ordering::*;

fn main() {
    let v:Vec<String> = std::env::args().collect();
    let a:u8 = v[1].parse().unwrap();
    let b:u8 = v[2].parse().unwrap();
    print!("{} is ", a);
    print!("{}", match a.cmp(&b) {
        Less => "less than",
        Equal => "equal to",
        Greater => "greater than"
    });
    print!(" {}", b);
}

Updated to match that

That's great, and welcome to PPCG :)

Haskell, 87 bytes
One byte shorter than Otomo's approach.
a?b=show a++" is "++["less than ","equal to ","greater than "]!!(1+signum(a-b))++show b

Nice solution.  :)

Python 2, 78 bytes
I love how cmp() is really useful, but it was removed in Python 3.
Using an anonymous function:
lambda a,b:`a`+' is '+['equal to ','greater than ','less than '][cmp(a,b)]+`b`

Not using a function (79 bytes):
a,b=input();print a,'is %s'%['equal to','greater than','less than'][cmp(a,b)],b

Isn't this a dupe of @TheNumberOne's answer?

@BetaDecay Nope. They are different. Read my comment on that answer.

Pyth, 57 55 53 bytes
AQjd[G"is"@c"equal to
greater than
less than"b._-GHH)

This basically does:
["less than", "greater than", "equal to"][sign_of(A-B)]

Saved 2 bytes thanks to @AlexA.'s suggestion of using A instead of J and K and another 2 bytes by replacing the whole addition mess with a simpler subtraction.
Live demo and test cases.
55-byte version
AQjd[G"is"@c"less than
greater than
equal to"b+gGHqGHH)

Live demo and test cases.
57-byte version:
jd[JhQ"is"@c"less than
greater than
equal to"b+gJKeQqJKK)

Live demo and test cases.

One byte shorter: AQs[Gd"is"d?<GH"less than"?>GH"greater than""equal to"dH

@AlexA. I just used the suggestion of A instead of J and K, which saved 2 bytes.

rs, 105 bytes
(\d+) (\d+)/\1 is (_)^^(\1) (_)^^(\2) \2
 (_+) \1_+/ less than
 (_+) \1 / equal to
_+ _+/greater than

The trailing and preceding whitespace is very important!
Live demo and all test cases.

O, 67 bytes
jJ" is ""greater than""less than""equal to"JjK-.e\1<+{@}d;;' K++++p

Live demo.

SWI-Prolog, 94 bytes
a(A,B):-(((A>B,C=greater;Ab="greater than "|a<b="less than "|1<3="equal to "
a#b=show a++" is "++a!b++show b

thanks to nimi
94 byte version:
d a|a>0="greater than "|a<0="less than "|1<3="equal to "
c a b=show a++" is "++d(a-b)++show b

97 byte version:
d a b|a>b=" greater than "|a<b=" less than "|1<3=" equal to "
c a b=show a++" is"++d a b++show b

my first time golfing :) (tested with ghci, size determined with du and stat)

You can save a few bytes by turning the functions d and c into operators, e.g. d becomes a!b|a>b=... and c becomes a#b=show a++" is"++a!b++show b. Example run: 41#51.

You need one more fix: d(a-b) --> a!b, and this byte counter tells me your score is then 88.

Thx - i missed that

Ruby 1.9+, 73 71 70 68 bytes
->a,b{[a,b]*" is #{%w{equal\ to greater\ than less\ than}[a<=>b]} "}

1 character shorter with word array: %w{equal\ to greater\ than less\ than}

Can shave two more characters using Array#*: ->a,b{[a,b]*" is #{%w{equal\ to greater\ than less\ than}[a<=>b]} "}

Swift, 105 92 byte
func c(a:Int, b:Int){println("A is",(a==b ?"equal to":(a<b ?"less":"greater")," than"),"B")}

even shorter with Swift 2.0 (103 90 byte)
func c(a:Int, b:Int){print("A is",(a==b ?"equal to":(ab?"greater than ":a$b?"greater than":($a<$b?"less than":"")))." B";}

100 byte version (thanks jrenk)
<?php function c($i,$u){echo$i.' is '.($i>$u?'greater than ':($i==$u?'equal to ':'less than ')).$u;}

I think you should replace "A" and "B" in the output with the numbers you get from the input.

You should count the "<?php" opening tag to your byte count. You can save a few bytes by just using ":" for 'less than' since it's the last case that could happen. Look here.

Awesome. Thanks for your help!

you can shorten it by 1 byte if you use: echo"$i is " instead of echo$i.' is '

PHP, 88 bytes

PHP function, 88 bytes:
function a($a,$b){echo"$a is ",$a-$b?($a>$b?"greater":"less")." than":"equal to"," $b";}
function b($a,$b){echo"$a is ",$a-$b?$a>$b?"greater than":"less than":"equal to"," $b";}
function c($a,$b){echo"$a is ",$a-$b?($a>$b?"greater":"less")." than $b":"equal to $b";}

Note than $a-$b can be replaced by $a^$b.

Full program, 89 bytes:
<?=$a=$argv[1]," is ",$a-($b=$argv[2])?($a>$b?"greater":"less")." than $b":"equal to $b";

I used:

String interpolation.
Nested ternary.
Some echo tricks, like using commas instead of concatenating or using PHP short echo tag.

JavaScript, 84 bytes
f=function(a,b){alert(a+' is '+(a-b?(a>b?'greater':'less')+' than ':'equal to ')+b)}

APL (Dyalog Unicode), 56 bytesSBCS
Anonymous infix lambda.
{∊⍺'is ','less than' 'equal to' 'greater than'[2+×⍺-⍵]⍵}

Try it online!
{…} "dfn"; left argument is ⍺ and right argument is ⍵:
 ⍵ the right argument  to the right of
 'less than' 'equal to' 'greater than'[…] this list of three strings indexed by:
  ⍺-⍵ left argument minus right argument
  × sign of that
  2+ add two to that
 ⍺'is ', prepend the left argument and the string "is "
 ∊ ϵnlist (flatten)

05AB1E, 30 bytes
.S“ž‰€„†ª€ëîØ€ë“#2ôè¹'€ˆ.À`²ðý

Try it online!

Befunge-93, 82 bytes
<v"equal to "$_v#!\!`0:\0:-&,,,"is ".::&
 v "less than "_" naht retaerg"
@>:#,_$-.

Try it online!

Thue, 181 bytes
1,1::=o,x
x1::=1x
x]::=]x
!x::=!o
11,]::=1o,]
[1,]::=!vo
vx::=>x
[,11::=[,1x
[,1]::=!<x
[,]::=!=
o::=~1
>::=~ is greater than
<::=~ is less than
=::=~ is equal to
*::=:::
::=
[*]

Try it online!
The TIO version contains a trailing newline, but that’s only needed in this specific implementation; the specification doesn’t specify that the trailing newline is needed and other interpreters (e.g.) don’t require it. Similarly, the newlines in the output don’t show up in the linked interpreter.
IO Format
Input and output are in unary strings of 1s, and there is a comma (but no spaces) between A and B. e.g. For A = 2 and B = 3, input 11,111.
Explanation (not really)
Unfortunately, my own motivation to write an explanation is inversely proportional to the reader’s desire for one, so I won’t write a detailed explanation. However, this ungolfed version that’s just split into sections might help (I’ll use # to denote comments):
# General stuff
1,1::=o,x
x1::=1x
x]::=]x
!x::=!o

# Check for greater than-ness
11,]::=1o,]
[1,]::=!vo
vx::=>x

# Check for less than-ness
[,11::=[,1x
[,1]::=!<x

# Check for equality
[,]::=!=

# Output
o::=~1
>::=~ is greater than
<::=~ is less than
=::=~ is equal to

# Input
*::=:::
::=
[*]

Look at the Input, Output, and General stuff sections first before looking at the other sections.
Also, maybe use this interpreter to step through some examples.
Original answer:
Thue, 48 bytes, non-competing due to output format
*::=:::
1_1::=_
1__::=~>
__1::=~<
___::=~=
::=
*

Try it online!
IO format
The numbers are inputted in unary as strings of 1s, with an underscore on either side and an underscore between them. For example, to compare 2 and 3, the input would be _11_111_.
If the input is _A_B_ then the output is > if \$A>B\$, < if \$A    If B becomes 0 but A remains positive, A > B.
__1::=~<    If A becomes 0 but B remains positive, A < B.
___::=~=    If both A and B become 0, A = B.
::=
*

TIO needs a trailing newline for some reason. Additionally, the description does seem rather strict on what the output should be i'm afraid

@JoKing Oh, I didn't notice that. Thanks for pointing it out! Since the output format looks very nontrivial to implement (since I have to output the actual values of A and B), I'll just keep my code as it is and mark it as noncompeting for now until I get around to correcting my answer.

Quipu, 154 bytes
'g'l'e\/' 3&5&2&[]1&' 4&
'r'e'q/\'i[][][]/\[]/\[]
'e's'u  's4&9&/\1@/\  /\
'a's'a  ' []<<1@??
't' 'l  /\--8&??
'e't'   \/  >>
'r'h't
' 'a'o
't'n
'h
'a
'n

Attempt This Online!
Explanation
Threads 0 through 2 store the strings greater than, less than, and equal to, respectively. Then:

Thread 3 inputs a number, stores it, and also outputs it
Thread 4 outputs  is , then inputs a number and stores it
Thread 5 calculates the value of thread 3 minus the value of thread 4
Thread 6 loads the value of thread 5 and:

jumps to thread 9 if it is less than 0
jumps to thread 8 if it is greater than 0
continues to thread 7 otherwise

Thread 7 loads the value of thread 2, outputs it, and jumps to thread 10
Thread 8 loads the value of thread 0, outputs it, and jumps to thread 10
Thread 9 loads the value of thread 1, outputs it, and continues to thread 10
Thread 10 outputs a space
Thread 11 loads the value of thread 4 and outputs it

Vyxal ṡ, 34 bytes
=[«ß‟₆nḭ«|<[`∨⅛`|`∆ḭ`]`λ⊍`]?^‛is?^

Try it Online!
=[«ß‟₆nḭ«|<[`∨⅛`|`∆ḭ`]`λ⊍`]?^‛is?^ # Takes 2 numbers as arguments
=[«ß‟₆nḭ«                  ]        # If equal, push the base compressed string "equal to"
         |                          # Otherwise...
          <[`∨⅛`     ]              # If less than, push the string "less"
                |`∆ḭ`               # Otherwise, push the string "greater"
                      `λ⊍`          # Push the string "than"
                           ?        # Push the first number (due to the input mode, this turns out to be the second input)
                            ^       # Reverse the stack so we can prepend stuff
                             ‛is    # Push the string "is"
                                ?   # Push the second number (first input)
                                 ^  # Reverse the stack again
                                    # Implicit output. ṡ joins the stack on spaces

Try it Online! for 30 bytes

C++, 109 bytes
#include<cstdio>
int x(int a,int b){printf("%d is %s %d",a,a>b?"greater than":a<b?"less than":"equal to",b);}

Common Lisp, 92 bytes
(lambda(a b)(format t"~A is ~[less than~;equal to~;greater than~] ~A"a(1+(signum(- a b)))b))

More readably:
(lambda(a b)
  (format t "~A is ~[less than~;equal to~;greater than~] ~A"
  a                   ; first ~A
  (1+(signum(- a b))) ; gives 0, 1 or 2 which selects a clause in ~[ ~]
  b                   ; second ~A
))

Good, but reversed. I ran it like ((lambda(a b)(format t"~A is ~[less than~;equal to~;greater than~] ~A"a(1+(signum(- b a)))b)) 10 20) in CLISP console and it yields 10 is greater than 20.

@pawel.boczarski Thanks a lot.

Inform 7, 109 bytes
To(A - value)T(B - value):say "[A] is [if A is B]equal to [else if A > B]greater than [else]less than ";say B

This defines a phrase used as 1 T 2;.

JavaScript, 92 bytes
a=+prompt(),b=+prompt();alert(a+" is "+(a>b?"greater than ":a<b?"less than ":"equal to ")+b)

PHP 7, 91 bytes
<?=$a=$argv[1],[~ß–ŒßšŽŠž“ß‹ß,~ß–Œß“šŒŒß‹—ž‘ß][($b=$argv[2])<=>$a]?:~ß–Œß˜šž‹šß‹—ž‘ß,$b;

Usage:
Save as ANSI in file.php and run:
php -derror_reporting=~E_NOTICE file.php A B

Is suppressing notices via CLI flag considered cheating? If so, here is a version that works with full error reporting, (93 Bytes)
<?=$a=$argv[1],@[~ß–ŒßšŽŠž“ß‹ß,~ß–Œß“šŒŒß‹—ž‘ß][($b=$argv[2])<=>$a]?:" is greater than ",$b;

Some Explanation
For the string constants, I used undefined constants and bitwise invert them with ~. PHP replaces undefined constants with the name of the constant (foo => "foo") and allows special characters in constant names. This way you can save a byte even for strings with whitespace. Example: ~ß => " ")
The spaceship operator <=> returns 0 if the operands are equal, -1 if the left operand is less than the right operand and 1 if the left operand is greater than the left operand. I use this as array index, to get " is equal to " and " is less than ". For the non-existing array key -1 the result is null and thanks to ?: we get " is greater than " in this case.

As long as the errors aren't output to STDOUT, suppressing them is fine

PowerShell, 98 85 Bytes
(Thanks to tomkandy for the huge assist on the param and reminding me that PowerShell likes inline subexpression parsing, so go ahead and use it)
param($a,$b);"$a is $(@("equal to","greater than","less than")[$a.CompareTo($b)]) $b"

Essentially the same, just trimmed down quite a bit.

(Original below)
Decently competitive, I was somewhat surprised. Again, the $ character and taking input is the downfall.
$a=$args[0];$b=$args[1];"$a is "+@("equal to","greater than","less than")[$a.CompareTo(+$b)]+" $b"

(Creating a function of two arguments is one byte longer than taking command-line input of two arguments, thanks to the } at the end)
function r{param($a,$b);<doing_stuff>}
$a=$args[0];$b=$args[1];<doing_stuff>

Expanded:
$a=$args[0]
$b=$args[1]
"$a is " + @("equal to","greater than","less than")[$a.CompareTo(+$b)] + " $b"

Similar in concept to some other languages present, this is utilizing a feature of x.CompareTo(y), which returns -1 if x<y, 0 if x=y, and 1 if x>y. We take that result and pull out the appropriate value from a dynamic array we just created, leveraging the fact that [-1] stands for the last item in the array.
Do note the + inside the CompareTo(+$b) statement -- an explicit cast to an Integer. If we left that off, it would try to utilize the String comparison instead, which yields odd behavior.

You can get this down to 85 bytes with param - you don't need to use function to do so, param will work in a script - and by using subexpressions param($a,$b);"$a is $(@("equal to","greater than","less than")[$a.CompareTo($b)]) $b"

Thanks @tomkandy ... I keep forgetting about the inline sub-expression expansion. And this is honestly the first I've come across using param not inside a function block; I've always stuck with $args ... guess that's what I get for being trained on VBScript and using objArg everywhere ...

Swift 2.0, 87 bytes
func g(a:Int,b:Int){print("A is",a==b ?"equal to":a<b ?"less than":"greater than","B")}

beeswax, 68 chars
Non-competing answer, as I finished creating beeswax in December 2015, long after the start of the challenge.
The natural number range of beeswax is 64 bit unsigned integers, so this should be a valid solution. I’ll post a solution for 64 bit signed integers soon.
_T~T~{` is `Kp`equal to `{
p`ht ssel`#L~EL#~`greater than `{
>`an `{

You can clone the full and latest version of my beeswax interpreter, including examples and language specification from my GitHub repo.

Julia, 90 79 chars
Arrays in Julia use 1-based indexing, so adding 2 to the cmp function is necessary for proper access to the array.
c(a,b)=print(a," is ",["less than ","equal to ","greater than "][cmp(a,b)+2],b)

Result:
julia> c(2,2)
2 is equal to 2
julia> c(1654654,0)
1654654 is greater than 0
julia> c(-99999999999,-654654654)
-99999999999 is less than -654654654

Mouse-2002, 73 bytes
Uses variables (lame, I know).
?a:?b:"A is "a.b.>["greater than"]a.b.<["less than"]a.b.=["equal to"]" B"

Explained:
? a: ? b:  ~ store input in a , b
"A is "               ~ print
a. b. > [           ~ testif
  "greater than"      ~ print
]
a. b. < [           ~ rinse && repeat
  "less than"
]
a. b. = [
  "equal to"
]
" B"

Pure stack version: 96 95 bytes
I had fun writing this one. It would be a LOT shorter if Mouse had a 2dup instruction, but I implemented it myself instead.
??#D;#D;"A is ">["greater than"]<["less than"]=["equal to"]" B"
$D&swap &dup &rot &rot &over @

How this works:
? ? #D; #D; ~ get some input, then 2dup twice
"A is "                ~ print this
> [                  ~ test if gtr
  "greater than"       ~ print this
]                      ~ fallthrough
< [                  ~ repeat for next two conditions
  "less than"
]
= [
  "equal to"
]
" B"

$D       ~ def D():
 &swap        ~ ( x y -- y x )
 &dup         ~        ( y x -- y x x )
 &rot         ~               ( y x x -- x x y )
 &rot         ~                        ( x x y -- x y x )
 &over        ~                                 ( x y x -- x y x y )
@

We need the 2dup instruction because comparison pops.
Stack operations FTW!
Edit: for the same stack effect but a byte less, the second swap in the 2dup implementation was changed to rot.

You have to actually print the numbers, not just "A" and "B".

@FlipTack Oh, well, the spec is wildly unclear and other answers have the same behaviour. I'll fix it later

Perl 6, 74 bytes
->\a,\b{say a~" is {<less equal greater>[1+(a <=>b)],<than to>[a==b]} "~b} # 74

Usage:
# give it a lexical name for ease of use
my &compare = ->\a,\b{ … }

compare 1,2;
compare 2,2;
compare 3,2;

say '';

compare "{ 2²⁵⁶ }\n", "\n{ 2²⁵⁶ + 1 }"

1 is less than 2
2 is equal to 2
3 is greater than 2

115792089237316195423570985008687907853269984665640564039457584007913129639936
 is less than
115792089237316195423570985008687907853269984665640564039457584007913129639937

Python 3, 78 bytes
Translation of TheNumberOne's, using a double conditional instead of cmp, doesn't do too badly imo.
lambda a,b:print(a,'is',[['equal to','greater than'][a>b],'less than'][ab)-(að“îØ€ë
ž‰€„
†ª€ë“«¶¡è¹… is«sð²J

I'm surprised there isn't already a 05AB1E answer. You can write almost any word in 05AB1E with just 2 bytes.
Try it online!

SmileBASIC, 84 bytes
INPUT A,B
S=B-A?A;" is ";MID$("greater equal toless ",SGN(S)*8+8,8);"than"*!!S;" ";B

Noether, 91 79 bytes
I~aP" is "PI~b{ab=}{"equal to"P}{ab>}{"greater than"P}{ab<}{"less than"P}" "PbP

Try it here!
Note that while Noether is based heavily on Fourier, I have sacrificed golfability for functionality.

PowerShell, 71 Bytes
param($a,$b)"$a is $($a-$b|% T*g "greater than;less than;equal to") $b"

an update to the existing powershell answer from 2 years ago.

J, 64 bytes
9;:inv@A.;&":,'is'~.@;cut@'equal to greater than less'{~1 2*>-<

Try it online!
equal to is joined by a non-break space.
1 2*>-<: –1, –2 if less; 0, 0 if equal; 1, 2 if greater than
;&":,'is'~.@; prepend is, then prepend A and B. Because 0, 0 yields equal to,equal to, there’s a ~. to remove duplicates.
9 A. to shuffle B to the last position.
;:inv@ join by spaces

Swift >=2.2, 85 bytes
func f(a:Int,b:Int){print(a,"is",a==b ?"equal to":(a>b ?"greater":"less")+" than",b)}

SwiftFiddle link
The two current Swift answers, both in Swift 2.0, are invalid because they print the literal letters "A" and "B" instead of the values given into the function. Other than that, this is pretty much identical to those two.
I can't find any Swift 2.0 or 2.1 compilers online, so I can't say for certain it works in those versions, but I don't see why it wouldn't. The function is f(_:b:) in Swift 2.2 and f(a:b:) in Swift >=3.0.

Thunno 2 ṡ, 30 bytes
ṛ‘~µ to%ɱṚ ċç%ƁÞ ċç‘'%/i¹s`is$

Attempt This Online!
Only works in \$\le 2.2.0\$. ATO is currently on v\$2.1.9\$.
To make this work in all versions use -ʂ instead of ṛ.
Explanation
ṛ‘...‘'%/i¹s`is$  '# Implicit input
ṛ                  # Compare the two inputs. Push -1 if a>b, 0 if a==b, 1 if a<b.
 ‘...‘             # Push compressed string "equal to%less than%greater than"
      '%/         '# Split it on "%"s to get ["equal to","less than","greater than"]
         i         # Index the number from before into this list
          ¹s       # Push the second input and swap
            `is    # Push the string "is"
               $   # And push the first input
                   # Implicit output of the stack joined by spaces


text:
An optimization version of the Hadamard problem
First, some definitions.
A Hadamard matrix is a square matrix whose entries are either +1 or −1 and whose rows are mutually orthogonal.  The Hadamard conjecture proposes that a Hadamard matrix of order 4k exists for every positive integer k.
A circulant matrix is a special kind of matrix where each row vector is rotated one element to the right relative to the preceding row vector. That is the matrix is defined by its first row.
It is known that, except for 4 by 4 matrices, there are no circulant Hadamard matrices.
A matrix with m rows and n >= m columns is partial circulant, if it is the first m rows of some circulant matrix.
The task
For each even integer n starting at 2, output the size of the largest partial circulant matrix with +-1 entries and n columns that has the property that all its rows are mutually orthogonal.
Score
Your score is the highest n such that for all k <= n, no one else has posted a higher correct answer than you.  Clearly if you have all optimum answers then you will get the score for the highest n you post. However, even if your answer is not the optimum, you can still get the score if no one else can beat it.
Languages and libraries
You can use any available language and libraries you like. Where feasible, it would be good to be able to run your code so please include a full explanation for how to run/compile your code in Linux if at all possible.
Leading entries

64 by Mitch Schwartz in Python

Python 2
Table up to n = 64, verified optimal with brute force up to n = 32:
 4  4 0001
 8  4 00010001
12  6 000001010011
16  8 0000010011101011
20 10 00010001011110011010
24 12 000101001000111110110111
28 14 0001011000010011101011111011
32 14 00001101000111011101101011110010
36 18 001000101001000111110011010110111000
40 20 0010101110001101101111110100011100100100
44 18 00010000011100100011110110110101011101101111
48 24 001011011001010111111001110000100110101000000110
52 26 0011010111000100111011011111001010001110100001001000
56 28 00100111111101010110001100001101100000001010100111001011
60 30 000001101101100011100101011101111110010010111100011010100010
64 32 0001100011110101111111010010011011100111000010101000001011011001

where 0 represents -1. If n is not divisible by 4 then m = 1 is optimal. Generated using this code (or small variations of it) but with more trials for higher n:
from random import *

seed(10)

trials=10000

def calcm(x,n):
    m=1
    y=x
    while 1:
        y=((y&1)<<(n-1))|(y>>1)
        if bin(x^y).count('1')!=n/2:
            return m
        m+=1

def hillclimb(x,n,ns):
    bestm=calcm(x,n)

    while 1:
        cands=[]

        for pos in ns:
            xx=x^(1<<pos)
            m=calcm(xx,n)

            if m>bestm:
                bestm=m
                cands=[xx]
            elif cands and m==bestm:
                cands+=[xx]

        if not cands:
            break

        x=choice(cands)

    return x,bestm

def approx(n):
    if n<10: return brute(n)

    bestm=1
    bestx=0

    for trial in xrange(1,trials+1):
        if not trial&16383:
            print bestm,bin((1<<n)|bestx)[3:]

        if not trial&1:
            x=randint(0,(1<<(n/2-2))-1)
            x=(x<<(n/2)) | (((1<<(n/2))-1)^x)
            ns=range(n/2-2)

            if not trial&7:
                adj=randint(1,5)
                x^=((1<<adj)-1)<<randint(0,n/2-adj)
        else:
            x=randint(0,(1<<(n-2))-1)
            ns=range(n-2)

        x,m=hillclimb(x,n,ns)

        if m>bestm:
            bestm=m
            bestx=x

    return bestm,bestx

def brute(n):
    bestm=1
    bestx=0

    for x in xrange(1<<(n-2)):
        m=calcm(x,n)
        if m>bestm:
            bestm=m
            bestx=x

    return bestm,bestx

for n in xrange(4,101,4):
    m,x=approx(n)
    print n,m,bin((1<<n)|x)[3:]

The approach is simple randomised search with hill climbing, taking advantage of a pattern noticed for small n. The pattern is that for optimal m, the second half of the first row often has small edit distance from the (bitwise) negation of the first half. The results for the above code are good for small n but start deteriorating not long after brute force becomes unfeasible; I would be happy to see a better approach.
Some observations:

When n is odd, m = 1 is optimal because an odd number of ones and negative ones can't add up to zero. (Orthogonal means dot product is zero.)
When n = 4k + 2, m = 1 is optimal because in order for m >= 2 we need to have exactly n/2 sign reversals among {(a1,a2), (a2,a3), ... (a{n-1},an), (an,a1)}, and an odd number of sign reversals would imply a1 = -a1.
The dot product of two rows i and j in a circulant matrix is determined by abs(i-j). For example, if row1 . row2 = 0 then row4 . row5 = 0. This is because the pairs of elements for the dot product are the same, just rotated.
Consequently, for checking mutual orthogonality, we only need to check successive rows against the first row.
If we represent a row as a binary string with 0 in place of -1, we can check orthogonality of two rows by taking bitwise xor and comparing the popcount with n/2.
We can fix the first two elements of the first row arbitrarily, because (1) Negating a matrix does not affect whether the dot products equal zero, and (2) We know that there must be at least two adjacent elements with same sign and two adjacent elements with differing sign, so we can rotate to place the desired pair at the beginning.
A solution (n0, m0) will automatically give solutions (k * n0, m0) for arbitrary k > 1, by (repeatedly) concatenating the first row to itself. A consequence is that we can easily obtain m = 4 for any n divisible by 4.

It is natural to conjecture that n/2 is a tight upper bound for m when n > 4, but I don't know how that would be proven.

It is very interesting that there is no solution with 16 rows and 32 columns. Do you have any  idea why?

@Lembik If I had an idea, I would have written it in the answer.

source: Stack Exchange

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

sort: votes


text:
Find the occurrences of a character in an input string
Challenge
Write a program that, given a string x which is 10 characters long and a character y, outputs the number of times character y occurs in string x.
The shortest program in bytes to do so wins.
Example
Input: tttggloyoi, t
Output: 3

Input: onomatopoe, o
Output: 4

This seems almost too easy of a challenge. Also why limit the input to 10, instead of no limit at all?

Needs a winning condition.

Feel free to rollback my edit if it doesn't agree with you

How flexible is the input format? Can we choose a different delimiter, like a space or newline? Can the string be in quotes? Can we take the letter first and the string second? Will the characters always be lower case letters? If not, which other characters can occur?

@DigitalTrauma I think the OP posted the question and just took off, so if we have any questions, we're probably going to edit in the answers

@BetaDecay fair enough - I only just looked at your edit - you made substantial quality improvements.

The OP didn't specify that functions are allowed. He just said write a program.

This looks suspiciously like a C interview question...

Also posted on GeeksforGeeks Q&A: Create a program that asks the user to input 10 letters..

@manatwork Good find. This question might be a problem if content on that site is under a restrictive license.

@Quentin Let's hope they were smart enough to use the shortest solution in their interview. ;)

Pyth, 3 bytes
/ww

Example run:
$ pyth -c '/ww'
sdhkfhjkkj
k
3

Of course, the user could input more or less than 10 letters on the first input, but we don't need to worry about what happens when the user violates the spec.

seems like that's not valid pyth anymore?

explanation please?

@MilkyWay90 Here's how you might use this: Try it online!. / just counts the number of occurences in the first input string of the second input string. w takes a line of input.

@isaacg oh, I see. Thank you!

Pyth - 3 bytes
A different, less obvious, Pyth answer of the same size. It folds counting over the input.
/FQ

Test Suite.

JavaScript, 32
(p=prompt)().split(p()).length-1

Bash, 24 characters
x=${1//[^$2]}
echo ${#x}

Sample run:
bash-4.3$ bash letter-count.sh tttggloyoi t
3

bash-4.3$ bash letter-count.sh onomatopoe o
4

Retina, 12 bytes
(.)(?=.*\1$)

Simply a regex which matches a character which is equal to the last character in the input (except itself). When given a single regex, Retina simply returns the number of matches.

Wow, I'm over here trying to do all sorts of fancy stuff with rs, and you beat me with lookaheads. +1

Python 3, 29 bytes
print(input().count(input()))

Meh, this was easy. Assumes that input is a ten letter string.

You copied me! :D

@isaacg Great minds think alike? ;D

If you don't need to read input, wouldn't f=lambda x,y:x.count(y) be shorter? (Sorry if this doesn't work, I'm on mobile and can't check)

@mbomb007 My mistake, thanks for clarifying.

Removing the brackets around print saves you a character print input().count(input()) or a,b=input();print a.count(b) with the same amount

@willem That assumes that the input is surrounded by speech marks... I don't currently know the acceptability of this

well the first one works, sorry edited the comment :-)

@willem It's the same thing with the speech marks :P

Alright, removing the brackets only works in python 2, and yes you're right about the quote marks, but I needed them in python 2 anyway. Also I saw some debate about that in the comments, so thought it was acceptable. Heres a +1

@mbomb007 http://meta.codegolf.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet

@undergroundmonorail Remembered it wrong, but still, the OP specified a program.

Labyrinth, 32 29 27 24 bytes
),}{)-
@ ,  +);__
!-`{:}

This reads the single character first, followed by the string in which to count, and assumes that there are no null-bytes in the string.
Explanation
The code starts with ),}, which sets the bottom of the stack to 1, reads the first character and moves it to the auxiliary stack for future use. The 1 will be our counter (the offset of 1 will be cancelled later and is necessary for the IP to take the required turns).
The IP will now move down to read the first character of the search string with ,. The value is negated with `, again to get the correct turning behaviour. While we're reading characters from STDIN, the IP will now follow this loop:
  }{)-
  ,  +);__
  `{:}

{:} makes a copy of the stored character code and + adds it to the current value. If the result is 0 (i.e. the current character is the one we're looking for), the IP moves straight ahead: - simply gets rid of the 0, ) increments the counter, {} is a no-op.
However, if the result after + is non-zero, we don't want to count the current character. So the IP takes a right-turn instead. That's a dead-end, so that code there is executed twice, once forwards and once backwards. That is, the actual code in this case becomes );___;)+-){}. ); just gets rid of that non-zero difference, ___ pushes 3 zeroes, but ; discards one of them. ) increments one of the two remaining two zeroes, + adds them into a single 1, - subtracts it from the counter and ) increments the counter. In other words, we've created a very elaborate no-op.
When we hit EOF, , pushes -1, which ` turns into 1 and the IP takes a right-turn. - subtracts the 1 from the counter (cancelling the initial offset). ! prints the counter and @ terminates the program.

C++ Template-Metaprogramming, 160 154 116 bytes
Just for the giggles.
Thanks to ex-bart for golfing it down!
template<int w,int x,int y,int...s>class A:A<w+(x==y),x,s...>{};A<0,'t','t','t','t','g','g','l','o','y','o','i',0>a;

Usage:
The first char in the template instanciation is the character to search.
Complile with clang -std=c++11 -c -> the result is at the beginning of the error message.
Occurences.cpp:1:66: error: too few template arguments for class template 'A'
template<int w,char x,char y,char...s>class A{static const int a=A<w+((x==y)?1:0),x,s...>::a;};
                                                             ^
Occurences.cpp:1:66: note: in instantiation of template class 'A<3, 't', '\x00'>' requested here
template<int w,char x,char y,char...s>class A{static const int a=A<w+((x==y)?1:0),x,s...>::a;};

Complile with gcc -std=c++11 -c -> the result is at the bottom of the error message.
Occurences.cpp: In instantiation of ‘const int A<3, 't', '\000'>::a’:
Occurences.cpp:1:64:   recursively required from ‘const int A<1, 't', 't', 't', 'g', 'g', 'l', 'o', 'y', 'o', 'i', '\000'>::a’
Occurences.cpp:1:64:   required from ‘const int A<0, 't', 't', 't', 't', 'g', 'g', 'l', 'o', 'y', 'o', 'i', '\000'>::a’
Occurences.cpp:2:62:   required from here
Occurences.cpp:1:64: error: wrong number of template arguments (2, should be at least 3)

Search for the A<3, 't', '\000'> and A<3, 't', '\x00'>
154 byte version
template<int w,char x,char y,char...s>class A{static const int a=A<w+(x==y),x,s...>::a;};
int a=A<0,'t','t','t','t','g','g','l','o','y','o','i','\0'>::a;

160 byte version:
template<int w,char x,char y,char...s>class A{static const int a=A<w+((x==y)?1:0),x,s...>::a;};
int a=A<0,'t','t','t','t','g','g','l','o','y','o','i','\0'>::a;

You can shorten ((x==y)?1:0) to just (x==y) to save about 6 bytes (I think).

Thanks--wanted to be sure that it is defined behaviour, because I wasn't sure what the standard said about bool to int conversion.

It's defined behavior.

Yep, now I know that, too. :) Thank you very much. (I thought maybe it would be implementation dependent.)

128 bytes: Use anonymous enum instead of static const. Use 0 instead of '\0' to terminate. Use int instead of char. Use a slightly different declaration to instanciate. Remove superflouos newline. template<int w,int x,int y,int...s>class A{enum{a=A<w+(x==y),x,s...>::a};};A<0,'t','t','t','t','g','g','l','o','y','o','i',0>a;. Checked with g++ and clang.

Nice, thanks - will change that

Uh, my previous example was actually 127 bytes.  I did't notice that my editor appended a newline at the end when saving.

Anyway, I found another version with 116 bytes, by doing the recursion to a base class.  That allows to keep everything in the template parameters: template<int w,int x,int y,int...s>class A:A<w+(x==y),x,s...>{};A<0,'t','t','t','t','g','g','l','o','y','o','i',0>a;.  Live example.

Snowman 1.0.2, 16 characters
~vgvgaSaLNdEtSsP

Surprisingly short. Explanation:
~      make all vars active (even though we only need two, we don't really care)
vgvg   get two lines of input
aS     split first line on second line
aL     length of the new array
NdE    decrement (because ex. "axbxc""x"aS -> ["a" "b" "c"] which is length 3)
tSsP   to-string and print

Nice work! I wouldn't have thought that a solution that short would be possible in Snowman.

PHP, 36 35 bytes
<?=substr_count($argv[1],$argv[2]);

Usage:

Call the script with two arguments.

php script.php qwertzqwertz q

PHP, 23 bytes
If you register global Variables (only possible in PHP 5.3 and below) you can save 12 bytes (thanks to Martijn)

<?=substr_count($a,$b);

Usage:

Call the script and declare global variables php script.php?a=qwertzqwertz&b=q

You can remove a space after the comma to get one byte less

If you have register globals you can do script.php?a=qwertzqwertz&b=q, and do <?=substr_count($a,$b);, 23 chars

@Martijn good idea thank you!

Perl, 21 16 characters
(13 characters code + 3 character command line option.)
$_=0+s/$^I//g

Sample run:
bash-4.3$ perl -it -pe '$_=0+s/$^I//g' <<< tttggloyoi
3

bash-4.3$ perl -io -pe '$_=0+s/$^I//g' <<< onomatopoe
4

bash-4.3$ perl -i5 -pe '$_=0+s/$^I//g' <<< 1234
0

Neat trick with <>!

You could save a byte by dropping -l and ensuring that your input has no trailing newline: echo -en 'onomatopoe\no' | perl -pe '$_=eval"y/".<>."//"'

And you can knock your total down to 16 with perl -pe '$_+=s/${\<>}//g'

That referencing trick is incredible. Thank you, @ThisSuitIsBlackNot.

Why is the += needed? = seems to work just as well (and should still work when the input happens to start with some digits).

@ex-bart, to get a nice round zero if the character is no found in the string.

@ex-bart Nice work, you found an edge case! echo -en '1234\n0' | perl -pe '$_+=s/${\<>}//g' gives 1234. Fix for a cost of 1 byte with perl -pe '$_=0+s/${\<>}//g'

@ex-bart Although that brings up another point...if the search character can be a special character like . or *, it needs to be escaped: perl -pe '$_=0+s/\Q${\<>}//g'. 19 bytes total (just one less than manatwork's original solution!)

Using the -i options to put in the second argument makes this shorter. echo -en 'tttggloyoi' | perl -it -pe '$_+=s/$^I//g' is 12 characters +1 for the -i which is a score of 13.

Great trick @chilemagic. But the count would be 15, because only -e is for free, everything else gets counted: -i is 2 + p is 1.

Bash + grep, 26 bytes
grep -o "$1"<<<"$2"|wc -l

Javascript (ES6), 26 bytes
(a,b)=>a.split(b).length-1

This quick'n'easy solution defines an anonymous function. To use it, add a variable declaration to the beginning. Try it out:

z=(a,b)=>(a.split(b)||[0]).length-1;

input1=document.getElementById("input1");
input2=document.getElementById("input2");
p=document.getElementById("a");
q=function(){
  setTimeout(function(){
    p.innerHTML=z(input1.value,input2.value)||0;
  },10);
};
input1.addEventListener("keydown",q);
input2.addEventListener("keydown",q);
<form>Text to search: <input type="text" id="input1" value="hello world!"/>
Char to find: <input type="text" id="input2" value="l"/></form>

Output:

3

EDIT: Oh, I see there's a very similar solution already. I hope that's OK.

Haskell, 21 bytes
a!b=sum[1|x<-a,x==b]

Julia, 26 25 bytes
f(s,c)=endof(findin(s,c))

The findin function returns the indices in the first argument at which the second argument is found as a vector. The length of the vector is the number of occurrences.
Saved one byte thanks to Glen O.

endof will save you a byte in place of length.

APL, 7 3 bytes
+/⍷

This creates a function train. It works by creating a vector of zeros and ones corresponding to the indices at which the character appears in the string (⍷). The vector is then summed (+/).
Saved 4 bytes thanks to kirbyfan64sos and NBZ!

Is APL curried like K? I would think you could just do something like +/⍷ then (I don't know APL, so I might be wrong).

@kirbyfan64sos The only curry I know is food so I'm not sure. But I'll look into it. Thanks for the suggestion!

@kirbyfan64sos Yes, it is called a function train, so +/⍷ would indeed work, but since we are looking for a single char, one might as well use = instead of ⍷.

T-SQL, 99 40 Bytes
SELECT 11-LEN(REPLACE(s,c,'')+'x')FROM t

Simply does a difference between the input string and the string with the character removed. Takes input from table t
Edit changed to remove an issue with counting spaces and to take into account current acceptable inputs for SQL.  Thanks @BradC for all the changes and savings

You shouldn't need all the scaffolding, just do SELECT LEN(s)-LEN(REPLACE(s,c,''))FROM t, where t is a pre-populated input table with fields s and c.

On another note, this code gives the wrong answer for strings like A B C D    that end in spaces (if you're asked to count spaces), since LEN ignores trailing spaces.

@BradC I think way back then, the rules around what was acceptable, especially around SQL was restrictive and unclear.  I'll have a look at fixing the space issue when I have a little time

I usually just pad the end and subtract one; in this case input is guaranteed to be exactly 10 characters, you could just hard code it as SELECT 11-LEN(REPLACE(s,c,'')+'x')FROM t

@BradC yeah, looking at this again, not sure why I allowed for variable length.  Making changes.

C++, 78 bytes
int main(int,char**v){int c=0,i=0;while(i<10)v[1][i++]==*v[2]&&++c;return c;}

Call like this:
$ g++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp && ./a.out tttggloyoi t; echo $?
3

Element, 23 bytes
__);11'[)\
~="0 1@][+]`

The newline is part of the program.  I am actually using it as a variable name.
This program basically works by storing the target character in a variable, keeping the current string on the top of the stack, and then looping the "chop, compare, and move result underneath" process, adding up the results in the end.
The newline as a variable name comes from using the newline at the end of input by chopping it off and storing into it.  The newline in the code is where I read from it.
Input is like this:
qqqqwwweee
q

Output is like this
4

Dyalog APL, 3 bytes
      +/=

I.e. "The sum of the equal bytes". E.g.:
      f ← +/=
      'onomatopoe' f 'o'
4

or just
      'onomatopoe'(+/=)'o'
4

K doesn't beat APL this time.
Try it online.

Please don't edit dozens of posts at once. You're completely flooding the front page. If there are many posts that need editing (which occasionally does happen, e.g. because a new tag is added), then it's generally nice to only do 3 of them at a time and then wait at least 12 hours so they can drop off the front page.

@MartinBüttner Yeah, I didn't realize at the time. :-( Regular users do not have the "Minor edit" option... I do realize why it cannot be available for everyone.

Unfortunately, there is no such option at all, not even for moderators.

Octave / Matlab, 33 bytes
sum(input('','s')==input('','s'))

Ruby, 22 20 bytes
p gets.count(gets)-1

Demo: http://ideone.com/MEeTd2
The -1 is due to the fact that gets retrieves the input, plus a newline character. Ruby's String#count counts the number of times any character from the argument occurs in the string.
For example, for the input [test\n, t\n], the t occurs twice and the \n occurs once, and needs to be subtracted.

You can remove $><< and reduce 4 bytes.

@VasuAdari but I need to print the result somehow...

can you not do this? -> p gets.count(gets)-1

@VasuAdari You're right; for the moment I thought that would put qutoes around the output, but it's numeric so it's OK. Thanks!

PowerShell, 32 Bytes
A four-for-one! And they're all the same length! :)
($args[0]-split$args[1]).Count-1

or
param($a,$b)($a-split$b).Count-1

Alternatively,
$args[0].Split($args[1]).Count-1

or
param($a,$b)$a.Split($b).Count-1

The first two styles use the inline operator -split, while the second two implicitly casts the first argument as a String and uses the .Split() string-based operator. In all instances an array is returned, where we must decrement Count by one, since we're getting back one more array item than occurrences of the second argument.
This one was kinda fun...

J, 5 bytes
+/@:=

I feel like J would have a built-in for this, but I haven't been able to find one - maybe one of the active J users can enlighten me. So instead this first applies = to the inputs, turning each character into 1 if it's equal to the requested one or 0 otherwise. Then +/ computes the sum of that list.

Batch File, 121 Bytes
Because I'm a masochist ...
SET c=0
SET e=_
SET t=%1%%e%
:l
SET a=%t:~0,1%
IF "%a%"=="%2" SET /A c+=1
SET t=%t:~1%
IF NOT "%t%"=="%e%" GOTO l
ECHO %c%

Warning: Assumes that _ doesn't occur in the input string. If it does, then the variable e needs to be adjusted appropriately.
This sets up our counter variable, c, and our end-of-string demarcation as _, before appending that to our input string %1 and setting the concatenated string to t. Then, we're entering loop :l, we set a temporary character variable a to be the first character of t, check if it matches our second input string %2 and increment c if true, then trim the first character off of t. Our end-of-loop condition checks t against our end-of-string demarcation, and loops back if not. We then echo out the value of our counter.
It would probably be possible to use a FOR loop instead, but that would necessitate enabling DelayedExpansion, which I think will actually be longer byte-wise than this. Verification of that is left as an exercise to the reader.

CJam, 5 bytes
ll/,(

Explanation
l      e# read x
 l     e# read y
  /    e# split x by y
   ,   e# count
    (  e# subtract one

><> (Fish), 30 bytes
0&v
=?\ilb
=?\:@=&+&l1
n&/;

Takes the string, then character to count. Input isn't separated (at least in the online interpreter). Try it on the online interpreter: http://fishlanguage.com I counted the bytes by hand, so let me know if I'm wrong.
Explanation
First off, ><> is 2 dimensional and and loops through a line or column until it hits a ; or error. This means that if it's proceeding left to right (like it does at the beginning of a program), it will wrap around the line if it reaches the end and is not moved or told to stop the program. Some characters per line will be repeated because they have different functions depending on the direction of the pointer, and the fourth line will have characters in reverse order because the pointer moves right to left.
A summary of the program is provided below.
Look at the instructions listed for ><> on esolangs to see what each individual character does.
Line 1: 0&v
0&v -put 0 into the register and change direction to down-up

Line 2: =?\ilb
(starting where line 1 moves the pointer to, i.e. the third character)
\ -reflect the pointer and make it move left-right
i -read input
lb=?\ -reflect downwards if there are 11 values in the stack

line 3: =?\:@=&+&l1
(starting at the third character)
:@ -duplicate y and shift the stack e.g. ['x','y','y'] -> ['y','x','y']
=&+& -increment the register if the character popped from x = y
l1=?\ -reflect downwards if there is 1 value in the stack

Line 4: n&/;
(starting at the third character)
/ -reflect right-left
&n; -print value of the register

Julia, 21 bytes
f(s,c)=sum(i->c==i,s)

Note that it requires that c be a char, not a single-character string. So you use it as f("test me",'e') (which returns 2) and not f("test me","e") (which returns 0, because 'e'!="e").

Ruby, 18 bytes
->s,c{p s.count c}

Usage:
->s,c{p s.count c}.call 'tttggloyoi', 't'

->s,c{p s.count c}.call 'onomatopoe', 'o'

Japt, 2 bytes
èV

Try it online!

Pip, 3 bytes
Joining the 3-byte cavalcade...
bNa

Read as "b in a". a and b are command-line arguments. The N operator, unlike its Python counterpart, doesn't just return a truth value; it returns the count.

R, 27 bytes
sum(strsplit(x,"")[[1]]==y)

Usage
sum(strsplit("tttggloyoi","")[[1]]=="t")
[1] 3
sum(strsplit("onomatopoe","")[[1]]=="o")
[1] 4

Or, Another one with 42 bytes
f<-function(x,y)length(gregexpr(y,x)[[1]])

Usage
f("tttggloyoi", "t")
[1] 3
f("onomatopoe", "o")
[1] 4

Javascript
Program, 48 chars
alert(prompt().match(/(.)(?=.*\1$)|$/g).length-1)

Function with 1 argument (ES6), 39 chars
f=s=>s.match(/(.)(?=.*\1$)|$/g).length-1

Function with 2 arguments (ES6), 28 chars
f=(s,c)=>s.split(c).length-1

rs, 33 bytes
+(.)(.* (?!\1).)/\2
(.*)../(^^\1)

Live demo and test cases.
This is pretty simple. The first line removes all characters except the ones we're counting. The next line counts the number of characters that are left, excluding the one we're searching for.
Takes input separated by spaces, e.g.:
onomatopoe o

C#, 36 51 48
Debug.Write(args[0].split(args[1][0]).Length-1);

Well now it will :) - Ofcourse I forgot the cw..

You could also use Console.Write instead of Console.WriteLine to save another 4 bytes.

I am such a fool -.-

Doesn't Debug.Write go to STDERR rather than STDOUT?

K, 3 bytes
+/=

K actually beat APL!!! :D Well, now it's a tie... :/
You can call it like this:
+/=["hello";"l"]

Or assign it to a variable first:
f:+/=
f["hello";"l"]

Also note that this does not work in oK. It does work in the official K2 and K5 interpreters, as well as Kona.

The original style of invocation (+/=["hello";"l"]) worked fine in oK. The latter case (f:+/=;f["hello";"l"]) was behaving incorrectly and should be fixed now.

@JohnE Uh, yeah. I was going to report that as a bug, but then I ended up entering another code golf challenge. :)

Nope, K doesn't beat APL this time. See my answer. You could call it a tie, but APL needs less additional chars during actual use.

O, 23 10 bytes
ie\i-e@-_p

Original:
0K;i""/iJ;l{J=K+:K;}dKp

I don't think I can get this any shorter... :/
Ah, I'm stupid. I forgot the traditional method of counting occurrences: subtract the string lengths.

STATA, 52 bytes
di _r(a)_r(b)
di 10-length(subinstr("$a","$b","",.))

Gets the two strings as inputs. Replaces all occurrences of the second string (the character) with empty string. Subtract that from 10, since the length of the first string is 10.
Unfortunately functions in STATA can't be shortened the same way that variable names and commands can. Also, this doesn't work in the online interpreter, since it doesn't include these functions.

scala, 31 bytes
(x:String,y:Char)=>x.count(y==)

Jelly, 1 byte
ċ

TryItOnline
The obvious implementation would be 3 bytes: s1ċ, which splits a string or list (left argument) into slices of length 1 with s1 and counts occurrences of the character (right argument) with ċ.
However, since the character will only ever be of length 1, we could, instead, inspect all non-empty contiguous slices of a string with Ẇ; the character will only ever match those slices that are of length 1.
...and since a string is an array of characters, the function can just be ċ.

A string is an array of characters. The problem is that "o" is a string, not a character. As a function, plain ċ is enough.

Wasn't sure of the rules on input, so made it a clause-1-byte-solution. Thanks!

Do the command line arguments have to be entered as I have done in the TIO link?

There's no way of entering characters in the CLAs, since i put uses Python's syntax. You'd have to call the link with “onomatopoe”ç”o or similar.

Java 7, 69 68 54 52 bytes
int c(String...a){return a[0].split(a[1]).length-1;}

Surprisingly enough there wasn't a Java answer yet..
14 bytes saved thanks to @Geobits!
If a completely flexible input is allowed, we can save an additional byte by having a String-array parameter (51 bytes):
int c(String[]a){return a[0].split(a[1]).length-1;}

Ungolfed & test code:
Try it here.
class M{
  static int c(String... a){
    return a[0].split(a[1]).length-1;
  }

  public static void main(String[] a){
    System.out.println(c("tttggloyoi", "t"));
    System.out.println(c("onomatopoe", "o"));
  }
}

Output:
3
4

To get rid of the regex/replace, split on the character and count the resulting length a.split(b+"").length-1; -14 :D

@Geobits Ah nice! Thanks. And here I thought I was smart by changing a.length-a.replace(b,"").length with a.replaceAll("[^"+b+"]","").length() to save a byte. xD

That was my original thought too (and I commented that first, but deleted), except I used the fixed 10 instead of a.length() since the length is fixed in the spec ;)

@Geobits Ah, good point. ;D But this is even better. ;) Also, managed to subtract an additional 2 bytes by changing the String+char parameters to String....

Good call. I always forget about the ...

APL (Dyalog Extended), 1 byteSBCS
⍧

Try it online!
⍧ is Count In

05AB1E, 1 byte
¢

First input is the character, second the string.
Try it online or verify both test cases at once.
Explanation:
¢  # Count the amount of occurrences of the first (implicit) input-character
   # in the second (implicit) input-string
   # (after which the result is output implicitly)

Zsh, 15 bytes
<<<${#1//[!$2]}

Try it online!
Similar to the bash answer, but more compact thanks to Zsh allowing both ${   //} and ${#   } in the same expansion.

Retina, 11 bytes
w`^(.)¶.*\1

Try it online!
Takes input as two lines - the first line is the character, the second is the string.
Could be 10 bytes if taking input as the character preprended to the string, but that felt a bit too cheaty.
Explanation
w`^(.)¶.*\1     # (implicit count stage as there is just one line)
w`              # Include overlapping matches for the pattern
   (.)          # Match a single character...
  ^             # ...at the start of the input...
      ¶         # ... and followed by a newline...
       .*       # ...then zero or more arbitrary characters...
         \1     # ...and then the first character again
                # (implicitly output the number of matches)

I'm pretty sure the ^ is unnecessary. If we can assume the string doesn't contain bad characters (seems like we can), ~\^ [\n] K`` works (Try it online!). This might be possible to golf using something similar to that.

Wren, 29 bytes
Very hard to golf.
Fn.new{|a,b|a.count{|i|i==b}}

Try it online!
Explanation
Fn.new{|a,b|                  // Anonymous function with parameters a & b
            a.count           // Count every item
                   {|i|       // that...
                       i==b}} // is equal to b

Wren, 36 bytes
Fn.new{|a,b|a.trim(a.trim(b)).count}

Try it online!
Explanation
Fn.new{|a,b|                       } // Uninteresting anonymous function
                   a.trim(b)         // Remove all occurences of b in a
            a.trim(         )        // Trim this result with a, keeping the removed occurences
                             .count  // Find the length of this result

naz, 92 bytes
2x1v2a2x2v8a2x3v1r2x4v1x1f3r3x2v3e3x4v2e1f0x1x2f1v1a2x1v1f0x1x3f1v3x3v4e1o0x1x4f9s1o1s1o0x1f

Works for any valid input string terminated with the control character STX (U+0002), with the character to search for appearing first (e.g. t, tttggloyoi).
Explanation (with 0x commands removed)
2x1v                 # Set variable 1 equal to 0
2a2x2v               # Set variable 2 equal to 2
8a2x3v               # Set variable 3 equal to 10
1r2x4v               # Store the first byte of the input string in variable 4
1x1f                 # Function 1
    3r               # Read the 3rd byte of input, then remove it from the input
                     # This has the effect of skipping over the comma and space
      3x2v3e         # Jump to function 3 if it equals variable 2
            3x4v2e   # Jump to function 2 if it equals variable 4
                  1f # Otherwise, jump back to the start of the function
1x2f                 # Function 2
    1v1a2x1v1f       # Load variable 1 into the register, add 1,
                     # and store the new value in variable 1
                     # Then, jump to function 1
1x3f                 # Function 3
    1v3x3v4e1o       # Load variable 1 into the register
                     # Jump to function 4 if the register equals variable 3
                     # Otherwise, output once
1x4f                 # Function 4
    9s1o1s1o         # Subtract 9 and output, then subtract 1 and output
                     # (outputs "10")
1f                   # Call function 1

Burlesque, 4 bytes
peCN

Try it online!
Takes input as "string" 'i to search string for i.
If special inputs are not allowed:
Burlesque, 6 bytes
pe-]CN

Try it online!
Takes input as two quoted strings.
pe  # Parse and evaluate
CN  # Count

Vyxal, 2 bytes
$O

Try it Online!

I have been outgolfed.

PowerShell, 75 Bytes (Single Run)
nv a (read-host).split(", ");foreach($b in $a[0]){if($b=$a[2]){$c++}};$c|oh

The above will only work once, will error if variables still have
  values from last run(run twice in same environment).
PowerShell, 82 Bytes (Infinite Use)
$c=0;nv a (read-host).split(", ")-f;foreach($b in $a[0]){if($b=$a[2]){$c++}};$c|oh

The above can be used any number of times in the same environment.

C, 55 bytes
t;c(char* i,char z){t=0;for(;*i;)t+=*i++==z;return t;}

Jelly, 2 bytes, non-competing
There is a one-byte Jelly solution, but that takes in the argument in a rather particular way. With 1 byte extra, we can just input test instead of ["t", ...]
fL

Try it online!
f   filter all elements from the first implicit input that are not in the second implicit input
    "onomatopoe" f "o" filters out all non-"o" chars --> oooo
 L  Get the length of the remainder.

W, 4 bytes
Basically the same algorithm as my second Wren answer.
Sttk

Ahead, 16 bytes
The first character on stdin is the counted character, and the remainder of stdin is the string.
i&>jlir
 @Or+=t<

Try it online!

Fortran (GFortran), 60 bytes
character a(10),b
read('(10a,a)'),a,b
print*,count(a==b)
end

Try it online!
Takes input as an 11 length string, the last char being b.

Factor, 16 bytes
[ histogram at ]

Try it online!
Oddly enough, I don't think Factor has a built-in for this. This is two bytes shorter than both
[ '[ _ = ] count ]

and
[ indices length ]

Thunno 2, 1 byte
c

Attempt This Online!
Built-in for "count"

J-uby, 6 bytes
:count

Attempt This Online!

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

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


text:
What is the shortest infinite loop statement in Java?
I'm working on a golf for Java and I need an infinite loop. Obviously, I don't want to spend any more bytes than I have to, especially in such an expressive language.
Assuming I have some code I want to run, obviously the baseline is set at while(1>0)/*stmt*/ or 10 additional characters for a single line and while(1>0){/*stmt1*//*stmt2*/} or 12 additional characters for multiple lines. I say additional because the code I want to loop forever (well, forever-ish... I may or may not want to break out of or return from the loop) will have a certain length, and then I must tack on additional characters to make it actually loop.
At first I thought this was the best I'd get, but I figured I'd throw it out to the experts to see if they can find a better one.

Or something like main();?

@jimmy23013 No, but you can do main(null).

@Ypnypn Or main(a) if main is declared as public static void main(String[]a).

Out of interest do Java compilers or JITs typically optimize tail-call recursion, or are these recursions limited by stack size?

Related: http://codegolf.stackexchange.com/questions/13152/shortest-code-to-produce-infinite-output?rq=1

@SteveJessop I imagine a lot of loops are unrolled, tail-recursion optimized, or many other tricks. I believe sometimes they will unroll the loop for part of the loop, but not for others - like for(i = 0; i < 100; i++) { /* stmts */ } will maybe unroll ten statements, and make the for loop execute ten times. Irrelevant from the source code perspective, but still super cool!

@jimmy23013 You may have provided me a way to do my the shortcut that prompted this question using recursion actually. It might not answer this particular question, but it might have made the underlying code I was making a bit shorter. It's not like I care how big my stack gets as long as it doesn't overflow!

A little off topic, I'm surprised we see more Java than Groovy here. If you like Java you should give Groovy a try for code golfing, It's Java with a lot of shortcuts : implicit main(), some of python syntax, a lot of overriden operators, truthy / falsey values, etc. ; In Groovy, while (1) would work.

Java very explicitly does not perform tail-call elimination. It's not actually an optimization because it modifies the semantics of programs. It obviously makes the difference between programs which crash on a stack overflow versus loop forever. It also impacts any code which inspects and manipulates stack traces.

@JohnE holy shit... I have only one word: CogParticle

@corsiKa: I'm not proud of all my past code. As Rufus says in Bill and Ted's Excellent Adventure, "they do get better..."

for(;;){}

It works cause no condition evaluates to always true.
Insert the code between the braces.
If you only got a few statements you can place them inside the head (the (;;) part. That the loop still runs is caused by when the condition statement is not a boolean it counts as always true.
Thanx to @Ypnypn for the reminder

If you have multiple statements, try to put all but one in the for loop itself. e.g., for(;;foo(),bar(),baz())quux();

you can exchange the empty braces for a semicolon for(;;);

@ratchetfreak Only if you don't intend to break the loop, but the OP that they do want the ability to break.

@ratchetfreak Yes I'm looking for both single and multi-line, although it's debatable whether Ypnypn's suggestion might actually be smaller. Either way, I should edit my post to make my objective more clear.

@Ypnypn I don't think that's legal syntax. There's no comma operator in Java (though it can be used in variable declarations).

Are we really allowed to post answers that aren't a function or a complete program?

50 bytes
interface M{static void main(String[]a){for(;;);}}

Java - 60 bytes (complete code)
I'm probably not interpreting the question correctly, but this code when compiled and run results in an infinite-ish loop, in that technically it should run forever, but usually it will exhaust the stack memory.
public class X{public static void main(String[]a){main(a);}}

On Coding Ground it ends quite quickly, on my Windows 7 laptop with advanced virtual memory management, it runs a long time, just making the system slower and slower.

problem with your solution is, it will give you quite quickly StackOverflowError so it hard to call it infinite loop

for(/*init*/;;/*stmt*/){/*stmt*/}

To save characters, you can use the init and increment parts of the loop to save a few bytes by using the semicolons.

How is this different than the accepted answer?

I'm just trying to make it more clear where the statements should go. One more thing: If you do need to use break, you can put it in the condition.

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


text:
Have you mooed today?
The Debian Linux distribution (and Debian-based distros, like Ubuntu, Kali and others) uses a package-manager called APT. To install program foo you would type into a terminal
sudo apt-get install foo

One little Easter Egg of APT is the following
apt-get moo

Which after typing will produce the following output
                 (__)
                 (oo)
           /------\/
          / |    ||
         *  /\---/\
            ~~   ~~
..."Have you mooed today?"...

You must write a program that produces this EXACT output in as few bytes as possible. (including trailing spaces and a new line)
Here is the same output with \n added to represent newline characters, and a * to represent trailing spaces
                 (__)*\n
                 (oo)*\n
           /------\/*\n
          / |    ||***\n
         *  /\---/\*\n
            ~~   ~~***\n
..."Have you mooed today?"...\n

As requested in the comments, here is the md5sum of the mooing.
35aa920972944a9cc26899ba50024115  -

I think it's APT, not aptitude; aptitude does not have Super Cow Powers

@aditsu oh, I guess I misunderstood what aptitude is. I thought aptitude is the name of apt-get.

For reference, could you post the output of apt-get moo|md5sum ?

Bash, 11 bytes: apt-get moo :P

I'm getting a different result from apt-get moo|md5sum on Ubuntu. One obvious difference is that it has much less leading space.

@RetoKoradi I presume that's intentional

@Dennis Doesn't work on Arch Linux ... cannot reproduce the result :P

$ aptitude moo (hint: try making the output more verbose ;) )

Bash, 95 bytes
0000000: 7a 63 61 74 3c 3c 27 27 0a 1f 8b 08 01 01 01 01 01  zcat<<''.........
0000011: 02 03 53 40 07 1a f1 f1 9a 0a 5c 98 c2 f9 f9 a8 c2  ..S@......\......
0000022: fa ba 60 10 a3 8f 2c aa af 50 03 a2 6a 40 24 42 58  ..`...,..P..j@$BX
0000033: 0b 28 11 03 54 ab 1f 83 6a 70 5d 1d 8c e0 d2 d3 d3  .(..T...jp]......
0000044: 53 f2 48 2c 4b 55 a8 cc 2f 55 c8 cd cf 4f 4d 51 28  S.H,KU../U...OMQ(
0000055: c9 4f 49 ac b4 57 02 ca 70 01                       .OI..W..p.

The above is a reversible hexdump. To create the file, execute
xxd -r -c 17 > 55918.sh

paste the hexdump and press Enter, then Ctrl + D.
To run created file, execute
bash 55918.sh 2>&-

Any other filename will do.
I chose zopfli as the compressor since it is compatible with the Coreutils program zcat and achieves better compression than gzip, bzip2 and xz.
zcat<<'' will read the following lines (until EOF) and feed them as input to zcat.
Note that zcat will print a warning (since I stripped the checksum of the compressed file), as will bash (since the HEREDOC isn't terminated by an empty line). These warnings are printed to STDERR (suppressed by 2>&-), which is allowed by default per consensus on Meta.

CJam, 96
This uses a lot of nasty bytes, so here's a hex dump of it:
00000000  22 ee 51 1e 53 41 15 ee  51 20 53 41 15 9a 5f 5a  |".Q.SA..Q SA.._Z|
00000010  b9 5f 41 15 8c 5f 41 f9  38 24 2a 15 7e 55 1c 5f  |._A.._A.8$*.~U._|
00000020  b9 30 5f b9 41 15 a8 26  2a 26 2a 15 36 45 91 c3  |.0_.A..&*&*.6E..|
00000030  ed cb 41 f3 df eb 41 db  20 cb c9 41 e9 df c9 c3  |..A...A. ..A....|
00000040  f3 7f 45 36 15 22 7b 69  32 6d 64 5c 5f 63 5c 37  |..E6."{i2md\_c\7|
00000050  6d 64 22 20 5f 6f 2d 7c  7e 2e 22 3d 2a 3f 7d 2f  |md" _o-|~."=*?}/|

You can run the file with the java interpreter; it may be necessary to use ISO-8859-1 encoding, such as:
java -Dfile.encoding=ISO-8859-1 …
Try it online
Equivalent (and much longer) ASCII version:
[238 81 30 83 65 21 238 81 32 83 65 21 154 95 90 185 95 65 21 140 95 65 249 56 36 42 21 126 85 28 95 185 48 95 185 65 21 168 38 42 38 42 21 54 69 145 195 237 203 65 243 223 235 65 219 32 203 201 65 233 223 201 195 243 127 69 54 21]:c
{i2md\_c\7md" _o-|~."=*?}/

Try it online
Explanation:
There are 7 characters that have repetitions:  _o-|~.. Each of them can be encoded as a number n from 0 to 6. For each repeating sequence, I am encoding both the character's index (n) and the number of repetitions (k) in a single byte: 2 * (k * 7 + n), written as a character with that code. And I am encoding any single characters as 2 * c + 1, where c is the ASCII code. Everything goes in the initial string, and the rest of the program is decoding it:
{…}/      for each character in the string
  i       convert to integer (extended-ASCII code)
  2md     integer division by 2, obtaining the quotient (q) and remainder (r)
           r decides whether it's a repetition or single character
  \_      swap q and r, and duplicate q
  c\      convert q to character and move it before the other q
           this is for the r=1 case (single character)
  7md     divide q by 7, obtaining the quotient (k) and remainder (n)
  "…"=    get the corresponding character from that string (decoding n)
  *       repeat the character k times
  ?       use the single character or the repetition, depending on r

Old version (109):
" H(_2)
 H(o2)
 B/-6\/
 A/ | 4|2 3
 9* 2/\-3/\
 C~2 3~2 3
.6"{_'M,48>&{~*}&}/3/"Have you mooed today?"`*N

Try it online

Pyth, 100
r"17 (__)
17 (oo)
11 /6-\/
10 / |4 ||3
9 *  /\\3-/\
12 ~~3 ~~3
3.\"Have you mooed today?\"3."9

Try it online: Demonstration
r"string"9 run-length-decodes the string.
edit:
Here's a 97 char solution: Demonstration. Very likely this is also 97 bytes (in iso-8859-1). But too tired for writing the bytes down and doing an explanation. Tomorrow evening, I guess.

GolfScript (107 bytes)
This is a very simple encoding: newlines are replaced with ^, and spaces are run-length-encoded. The result contains some non-printable characters, so I present it here as xxd output:
0000000: 2711 285f 5f29 015e 1128 6f6f 2901 5e0b  '.(__).^.(oo).^.
0000010: 2f2d 2d2d 2d2d 2d5c 2f01 5e0a 2f01 7c04  /------\/.^./.|.
0000020: 7c7c 035e 092a 022f 5c2d 2d2d 2f5c 015e  ||.^.*./\---/\.^
0000030: 0c7e 7e03 7e7e 035e 2e2e 2e22 4861 7665  .~~.~~.^..."Have
0000040: 0179 6f75 016d 6f6f 6564 0174 6f64 6179  .you.mooed.today
0000050: 3f22 2e2e 2e27 7b2e 3332 3c7b 2220 222a  ?"...'{.32<{" "*
0000060: 7d2a 7d25 225e 222f 6e2a 0a              }*}%"^"/n*.

Online demo
Note that this is one character shorter than the corresponding CJam code. The tradeoff is using ' as the delimiter for the main string (saving two \s to escape the "), saving an i to convert character values to integers in the decoding loop, and getting a free trailing newline; vs having character literals to replace the single-character string literals.

Since this question was briefly tagged printable-ascii, I also made a version with only (108) printable characters:
'Y(__)I
Y(oo)I
S/------\/I
R/I|L||K
Q*J/\---/\I
T~~K~~K
..."HaveIyouImooedItoday?"...'{.82-.*82<{72-' '*}*}%

Instead of encoding the run-lengths of the spaces as characters ^A to ^R (and encoding ^J as ^ to avoid collisions), it leaves newlines untouched and encodes the run-lengths as I to Y.
Incidentally, my general-purpose GolfScript Kolmogorov program produces a 120-byte program.

><>, 217 bytes
!v"                 (__) "a"                 (oo) "a"           /------\/ "a"          / |    ||   "a"         *  /\---/\ "a"            ~~   ~~   "a"..."c3*2-"Have you mooed today?"c3*2-"..."a!
 >r>l0)?v;
    ^   o<

Unfortunately this is a pretty boring answer.  It starts by reading out a string that draws out the entire cow, with newlines made by adding a value of 10 to the stack (a).  It then goes into a loop which just draws out the cow.
I originally made a loop to add in a set of spaces, but it was actually more expensive byte wise than just putting spaces in.
EDIT:  Forgot that fish is written as "><>"

Lua, 186 178 bytes
8 bytes saved thanks to a suggestion by @DJ McMayhem
p=print s=" "a=s:rep(17)b=s:rep(9)p(a.."(__) ")p(a.."(oo) ")p(b.."  /------\\/ ")p(b.." / |    ||   ")p(b.."*  /\\---/\\ ")p(b.."   ~~   ~~   ")p"...\"Have you mooed today?\"..."

Ungolfed:
p=print --Save the print function for later use
s=" " --Space character
a=s:rep(17) --string.rep(string, times) repeats the given string
b=s:rep(9)
p(a.."(__) ") --print out the lines
p(a.."(oo) ")
p(b.."  /------\\/ ")
p(b.." / |    ||   ")
p(b.."*  /\\---/\\ ")
p(b.."   ~~   ~~   ")
p"...\"Have you mooed today?\"..."

You could save 5 bytes by replacing line 2 with a=repeat(" ",17)

Ah thank you :) i was trying to figure out if i could do something like that...

PowerShell, 144 bytes
$a="        "
"$a$a (__) "
"$a$a (oo) "
"$a   /------\/ "
"$a  / |    ||   "
"$a *  /\---/\ "
"$a    ~~   ~~   "
'..."Have you mooed today?"...'

The above code will work properly in environments that print Unix-style newlines (\n). It produces the correct output with, e.g., Pash on Linux.
Mathematically, for PowerShell, having 8 spaces for the $a variable is the optimal, as less means too many additional spaces between the variable and the cow to make a $b worthwhile, and more means we can't double-up on the first two lines for the head.

I would argue that the "newline character" is locale/platform dependent, making your output as eligible as any other.

There's no such thing as a "newline character". \r is a carriage return, \n is a linefeed. Together, \r\n forms a newline on Windows. 2. PowerShell is not Windows only. I have tested your code with Pash (an open-source implementation of Windows PowerShell for Mono) and the output has the proper MD5 hash. 3. Because of the above, I took the liberty to unwiki your post. If you disagree with this, please re-wiki it.

Very interesting, @Dennis ... I'm aware of the differences between \r\n and \n, but like I said, I couldn't get the MD5 correct on Windows without something egregious. Thanks for that edit, though. First I've heard of Pash, too, so thanks for that as well. I wonder how complicated that would be to build under Cygwin ... ;-)

Molecule, 145 bytes
"   "_____:a"  (__)
";a____"  (oo)
";a__"  /------\\/
";a__" / |    ||
";a__"*  /\\---/\\
";a____"~~"b"~~
...\"Have you mooed today?\"..."

My first time trying to compress ASCII art :P

Vyxal, 101 bytes
‛_oƛ` (`pøṀ22↳,;\/:3-øṀp20↳₴ð,₀`/ | `꘍3\|꘍m+,9`*  /\---/\ `꘍,12‛~~꘍3\~꘍m+,`..."`:₴`λɾ λ• mo⋎Þ ¬¾?`₴Ṙ,

Try it Online!
Uses some form of compression.