128
\$\begingroup\$

Your favourite programming language has just had a birthday. Be nice and sing it the Happy Birthday song.

Of course you should accomplish this by writing a program in that language. The program takes no input, and writes the following text to the standard output or an arbitrary file:

Happy Birthday to You
Happy Birthday to You
Happy Birthday Dear [your favourite programming language]
Happy Birthday to You

You should substitute the bracketed part (and omit the brackets).

This is a code golf — shortest code wins.

UPDATE

I'm glad that the question aroused great interest. Let me add some extra info about scoring. As stated originally, this question is a code golf, so the shortest code is going to win. The winner will be picked at the end of this week (19th October).

However, I'm also rewarding other witty submissions with up-votes (and I encourage everybody to do so as well). Therefore although this is a code-golf contest, not-so-short answers are also welcome.

Results

Congratulations to Optimizer, the winner of this contest with his 42 byte long, CJam submission.

Leaderboard

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

/* Configuration */

var QUESTION_ID = 39752; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 48934; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });  
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];
  
  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });
    
    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    
  });
  
  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;
    
    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (/<a/.test(lang)) lang = jQuery(lang).text();
    
    languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang > b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<div id="language-list">
  <h2>Winners by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>

\$\endgroup\$
15
  • 3
    \$\begingroup\$ Can we count the name of the programming language as one byte because it would only seem fair to people coding in a long-winded language such as JavaScript vs. someone doing it in C. We are really looking for most creative logic right? \$\endgroup\$
    – MonkeyZeus
    Oct 13, 2014 at 18:49
  • 16
    \$\begingroup\$ Why all the upvotes for this despite all the downvotes for the Bonbon song? This is just as boring a challenge. \$\endgroup\$
    – xnor
    Oct 14, 2014 at 7:15
  • 10
    \$\begingroup\$ I should probably mention that the song is copyrighted and distributing these programs may cause a DMCA \$\endgroup\$ Oct 14, 2014 at 14:38
  • 13
    \$\begingroup\$ guys! Happy Birthday song is now in public domain!! \$\endgroup\$
    – Optimizer
    Sep 23, 2015 at 10:01
  • 5
    \$\begingroup\$ At least one of the answers prints a leading newline. Is that allowed? \$\endgroup\$
    – Dennis
    Jun 19, 2016 at 21:32

201 Answers 201

1 2 3
4
5
7
1
\$\begingroup\$

C: 87

#define p(a)printf("Happy birthday %s\n",a?a:"to you");
main(){p(0)p(0)p("dear C")p(0)}

Demo

Compiles fine, but since it doesn't return, it might not exit correctly. If you want it to return 0, it'll cost another seven characters:

#define p(a)printf("Happy birthday %s\n",a?a:"to you");
main(){p(0)p(0)p("dear C")return!p(0)}

Demo

\$\endgroup\$
1
\$\begingroup\$

Burlesque - 55 Characters

"Happy Birthday to You"4.*g_15.+"Dear Burlesque".+2iauN

Test it here.

\$\endgroup\$
1
  • \$\begingroup\$ "Happy Birthday " "to You"4.*"Dear Burlesque"3ia?+uN would be a shorter version. \$\endgroup\$
    – mroman
    Sep 25, 2015 at 11:45
1
\$\begingroup\$

Python 85

[print('Happy Birthday %s'%('dear Python' if x==2 else 'to you')) for x in range(4)]
\$\endgroup\$
1
  • 2
    \$\begingroup\$ The if/else idiom can be generally shortened to a list selection: ['to you','dear Python'][x==2]. Instead of string formatting %, you can just use string concatenation. Take a look at some Python golf tips: codegolf.stackexchange.com/questions/54/… \$\endgroup\$
    – xnor
    Oct 14, 2014 at 7:05
1
\$\begingroup\$

Cobra - 78

class P
    def main
        print (t=(l='Happy Birthday ')+'to You\n')+t+l+'Dear Cobra\n'+t
\$\endgroup\$
1
\$\begingroup\$

Befunge: 103

 >"yadhtriB yppaH"67+>:#,_1g:"0"-v
2^_@#-"0"g20p10-1,,,,,,," to You"_1+01p"egnufeB raeD ">:#,_"0"02p#
1
\$\endgroup\$
1
\$\begingroup\$

Railo CFML (79 characters)

for(i=1;i<5;i++){writeoutput("<br>Happy Birthday "&(i<>3?"to you":"dear CF"));}

Just having some fun creating a ridiculous mess:

  variables.endings = ["H,a,p,p,y, ,B,i,r,t,h,d,a,y, ,t,o, ,y,o,u","H,a,p,p,y, ,B,i,r,t,h,d,a,y, ,t,o, ,y,o,u","H,a,p,p,y, ,B,i,r,t,h,d,a,y, ,d,e,a,r, ,C,o,l,d, ,F,u,s,i,o,n,n,n,n,n","H,a,p,p,y, ,B,i,r,t,h,d,a,y, ,t,o, ,y,o,u"];
  variables.iVerse = '';
  for (i = 1; i <= ArrayLen(variables.endings); i++) {
    variables.iLine = '';
    for (i2 = 1; i2 <= ListLen(variables.endings[i]); i2++) {
      iLine = iLine & ListGetAt(variables.endings[i],i2);
    }
    variables.iVerse = variables.iVerse & variables.iLine;
    if (i < ArrayLen(variables.endings)) {
      variables.iVerse = variables.iVerse & "<br />";
    }
  }

  writeOutput(variables.iVerse);
\$\endgroup\$
2
  • \$\begingroup\$ I know it's a little obvious what language this is, but please, describe what language you used and the character count of your code. Also, try to shorten it as much as you can. \$\endgroup\$ Oct 13, 2014 at 22:57
  • \$\begingroup\$ @g.carvalho97 I was having too much fun, sorry. I'll fix it. \$\endgroup\$
    – Regular Jo
    Oct 13, 2014 at 23:01
1
\$\begingroup\$

Bc: 62 characters

(This demonstrates the language's only golfing strength: string literals are displayed even without the print statement.)

while(i++<4){"Happy Birthday "
if(i-3)"To You
"else"Dear bc
"}

Sample run:

bash-4.3$ bc <<< 'while(i++<4){"Happy Birthday "
> if(i-3)"To You
> "else"Dear bc
> "}'
Happy Birthday To You
Happy Birthday To You
Happy Birthday Dear bc
Happy Birthday To You
\$\endgroup\$
1
\$\begingroup\$

Python 3 - 61

Based on @Falko's answer I made one for Python 3.3. I slightly improved his code by removing the space at the beginning of "Dear Python" and using the space between 'Birthday' and 'to'.

H="\nHappy Birthday to You"
print((H*3)[:60]+"Dear Python"+H)

Total number of characters is 60 61.(thanks for the recount @manatwork)

Edit:

Two slightly different approaches, all with the same number of characters:

T="\nHappy Birthday to You"
print(T*2+T[:-6]+"Dear Python"+T)

or

print(T*2+T[:16]+"Dear Python"+T)

BTW: I would like to post this as a comment, but I do not have the rep.

\$\endgroup\$
2
  • \$\begingroup\$ Sure about the 60 characters? Seems 61 to me. \$\endgroup\$
    – manatwork
    Oct 14, 2014 at 9:28
  • \$\begingroup\$ @manatwork: you are right. Somehow my character counter gave the wrong output. It is also logic that I loss one character compared with Falko, because I need two parentheses and win one character by changing the "Dear Python" phrase. \$\endgroup\$
    – Hennep
    Oct 14, 2014 at 9:33
1
\$\begingroup\$

J : 53 bytes

'Dear J'(57+i.6)"_}'to You',"1~,~,:~'Happy Birthday '

,"1~,~,:~ and (57+i.6)"_ can probably be golfed further.

\$\endgroup\$
1
\$\begingroup\$

Pascal (83) in maXbox

  const H='Happy Birthday to You';
  Speak(H+H+DelString(H,'to You')+'Dear Pascal'+H);

See more: https://github.com/maxkleiner/maXbox3/releases

\$\endgroup\$
1
\$\begingroup\$

VBScript (75)

h="Happy Birthday "
l=vbLF
t="to You"&l
x=h&t
WScript.Echo x&x&h&"Dear VBS"&l&x

69 bytes if replacing WScript.Echo with MsgBox would be allowed.

\$\endgroup\$
1
\$\begingroup\$

Rexx: 87

p='a'x;h='Happy Birthday';i='to you';ooray='dear Rexx'p;!=h i;say h i p   h i p   h ooray !

Output:

Happy Birthday to you 
 Happy Birthday to you 
 Happy Birthday dear Rexx
 Happy Birthday to you
\$\endgroup\$
1
\$\begingroup\$

C# (Full program) - 162

namespace O{class P{static void Main(string[] a){for(int i=0;i<4;)System.Console.Write("Happy Birthday {0}\n",++i==3?"Dear god why do I golf in C#?":"to you");}}}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ "Dear god why do I golf in C#?" -- Try vba, it's worse. \$\endgroup\$
    – RubberDuck
    Oct 16, 2014 at 20:32
1
\$\begingroup\$

Falcon: 61

for i in[:4]:>"Happy Birthday "+(i==2?"Dear Falcon":"to You")
\$\endgroup\$
1
\$\begingroup\$

Javascript, 82

Yet another different js entry

a='Happy Birthday %s';b='to You\n';console.log(a+a+a+a,b,b,'Dear Javascript\n',b)
\$\endgroup\$
1
\$\begingroup\$

J Script(63)

alert((a=(x="\nHappy Birthday ")+"to You")+a+x+"Dear JScript"+a)

Why J Script and not Java Script? -3 bytes:)

\$\endgroup\$
4
  • \$\begingroup\$ I don't see why this has been downvoted... \$\endgroup\$
    – Beta Decay
    Oct 14, 2014 at 18:06
  • 1
    \$\begingroup\$ @BetaDecay coz JS is not the language name. \$\endgroup\$
    – Optimizer
    Oct 16, 2014 at 19:13
  • \$\begingroup\$ @Optimizer Ah, I see now... \$\endgroup\$
    – Beta Decay
    Oct 16, 2014 at 19:18
  • \$\begingroup\$ @Optimizer now it is the language name. \$\endgroup\$
    – MegaTom
    Oct 16, 2014 at 22:37
1
\$\begingroup\$

Clojure -- 79

(map #(println"Happy Birthday"%)(assoc(vec(repeat 4"to You"))2"Dear Clojure"))
\$\endgroup\$
1
\$\begingroup\$

PHP - 87 80 78 chars

<? $h="<br>Happy birthday ";$t="to you";$d="dear PHP";echo "$h$t$h$t$h$d$h$t";

I don't think that PHP is a good language for golfing, but I'm still practicing. And I love PHP :)

For the command line (strip off the short tags and replace the <br> with \n) 73 chars:

$h="\nHappy birthday ";$t="to you";$d="dear PHP";echo "$h$t$h$t$h$d$h$t";
\$\endgroup\$
3
  • 1
    \$\begingroup\$ I think you can skip the <? ?> because you can run it with -r on the command line. \$\endgroup\$
    – hmatt1
    Oct 13, 2014 at 20:28
  • 2
    \$\begingroup\$ Even on a webpage, you don't need the closing ?>, two more chars saved. \$\endgroup\$ Oct 17, 2014 at 15:55
  • 1
    \$\begingroup\$ @OlivierTheOlive Thanks. My PHP is a little rusty, I've not used it for a long time. \$\endgroup\$ Oct 17, 2014 at 18:16
1
\$\begingroup\$

C# (83)

using System;

for(int i=0;i<4;i++)Console.WriteLine("Happy Birthday "+(i!=2?"to You":"Dear C#"));

//Happy Birthday To You
//Happy Birthday To You
//Happy Birthday Dear C#
//Happy Birthday To You

Equally short (83 Bytes of code) is:

int i=0;while(i<4)Console.WriteLine("Happy Birthday "+(i++!=2?"to You":"Dear C#"));
\$\endgroup\$
1
\$\begingroup\$

Clojure (104 76 characters)

(let[h "Happy Birthday" t "to You\n"](print h t h t h "Dear Clojure\n" h t))

which prints

Happy Birthday to You
 Happy Birthday to You
 Happy Birthday Dear Clojure
 Happy Birthday to You
\$\endgroup\$
1
\$\begingroup\$

Rant, 58 54 chars

[r:4]{Happy Birthday [alt:[nth:3;Dear Rant];to You]\N}

Online Version

How it Works:

  • [r:4] - Sets repetitions of next block to 4.
  • [alt: ... ; ...] - Executes alternate code if a primary pattern prints nothing.
    • [nth:3;Dear Rant] - Prints "Dear Rant" on the third iteration.
    • If the nth condition is not satisfied, the alt function prints to You.
\$\endgroup\$
1
\$\begingroup\$

Intersystems Cache M, (71)

S X="Happy Birthday "
S Y="to You"
S Z="Dear M"
W X,Y,!,X,Y,!,X,Z,!,X,Y

Sample run...

USER>S X="Happy Birthday "

USER>S Y="to You"

USER>S Z="Dear M"

USER>W X,Y,!,X,Y,!,X,Z,!,X,Y
Happy Birthday to You
Happy Birthday to You
Happy Birthday Dear M
Happy Birthday to You
\$\endgroup\$
1
\$\begingroup\$

Delphi - 124 122 115

Another Delphi XE2 try, this time without a loop.

{$APPTYPE CONSOLE}const l=#13#10;y='to you'+l;h='Happy birthday ';d='dear Delphi'+l;begin
Write(h+y+h+y+h+d+h+y)end.
\$\endgroup\$
2
  • \$\begingroup\$ Write is enough there as the "Ln" part you output literally. \$\endgroup\$
    – manatwork
    Oct 17, 2014 at 9:08
  • \$\begingroup\$ And again you're right :) \$\endgroup\$
    – R-D
    Oct 17, 2014 at 9:20
1
\$\begingroup\$

Befunge, 90

Try it out here or here

4v>$"uoY ot"     v
v>0" yadhtriB yppaH" >:#,_$
< |-2\+49\0:
 v>"egnufeB raeD">:#,_$1-:!#@_
\$\endgroup\$
2
  • \$\begingroup\$ If I recollect correctly \r is the Mac OS linebreak; \r\n is the Windows linebreak; and \n is the *nix linebreak. \$\endgroup\$ Oct 22, 2014 at 2:52
  • \$\begingroup\$ Oops, yes I meant Mac (prior to OS X anyway). Apparently any of these line breaks should work according to the Funge-98 specs. I just checked the interpreter at compileonline.com and it seems happy to accept \r so I'll go with that. \$\endgroup\$
    – r3mainer
    Oct 22, 2014 at 8:11
1
\$\begingroup\$

C++, 107

Nice:

#include <iostream>
int main(){[](){}();//<-Good Luck Charm
    for (auto b : {false, false, true, false})
        std::cout << "Happy Birthday " << (b ? "Dear C++" : "To You") << '\n';
}

Golfed:

#include <iostream>
int main(){for(int b:"\0\0?")std::cout<<"Happy Birthday "<<(b?"Dear C++":"To You")<<'\n';}
\$\endgroup\$
6
  • \$\begingroup\$ How should I compile this? gcc without any switch says: “nwp.cpp:2:22: error: range-based ‘for’ loops are not allowed in C++98 mode”. \$\endgroup\$
    – manatwork
    Oct 22, 2014 at 17:50
  • \$\begingroup\$ @manatwork -std=c++11 should do the trick. \$\endgroup\$
    – nwp
    Oct 22, 2014 at 18:04
  • \$\begingroup\$ Nope. :( pastebin.com/eZUpZXve BTW, its gcc 4.8.2 on Linux. As neither the ungolfed version compiles, I suppose on my side is broken something… \$\endgroup\$
    – manatwork
    Oct 22, 2014 at 18:19
  • \$\begingroup\$ @manatwork Looks like gcc does not find the standard library. I don't know how exactly to fix that. You can semi-run the code at ideone. \$\endgroup\$
    – nwp
    Oct 22, 2014 at 18:49
  • \$\begingroup\$ @manatwork Now I remember. Ignore the standard library comment. Instead of gcc use g++ to compile. \$\endgroup\$
    – nwp
    Oct 22, 2014 at 23:40
1
\$\begingroup\$

sh - 59

echo "${h=Happy Birthday }${y=to You}
$h$y
${h}Dear sh
$h$y

I thought this solution would be worth sharing too, even though there's a shorter one.

\$\endgroup\$
1
\$\begingroup\$

K, 45 bytes

No one has sung Happy Birthday for everyone's favorite in-memory columnar database language? There, there:

`0:4 21#(57#"Happy Birthday to You"),"Dear K"

Very similar to the APL approach by @Moris Zucca- repeat the string Happy Birthday to You slightly more than two times and then glue on the Dear K. Reshaping into a 4x21 matrix repeats the initial line. In K, sending text to stdout requires the 0: IO verb. Without it (for 3 fewer characters), we would print:

  4 21#(57#"Happy Birthday to You"),"Dear K"
("Happy Birthday to You"
 "Happy Birthday to You"
 "Happy Birthday Dear K"
 "Happy Birthday to You")

An alternate 47 character solution I considered was:

`0:("Happy Birthday ",("to You";"Dear K")2=)'!4

This is about as straightforward as it gets- map a function over the sequence 0 1 2 3 given by !4, select the second half of the verse based on whether this index is equal to 2, glue on the start of the verse and then print the whole list out.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ There's no in-memory columnar database language I like better. \$\endgroup\$
    – Dennis
    Jun 28, 2015 at 20:56
1
\$\begingroup\$

JMP/JSL, 67

Like the Mathematica example by David Carraher, this will 'sing' (...read) the Happy Birthday message to you out loud.

speak(x="\!nHappy Birthday";y=x||" to You";y||y||x||" Dear JSL"||y)

Output:

Happy Birthday to You
Happy Birthday to You
Happy Birthday Dear JSL
Happy Birthday to You

For 7 less bytes you will have the Happy Birthday message printed for you in the log

\$\endgroup\$
1
\$\begingroup\$

SAS, 66 bytes

data;a='Happy Birthday';b=a||' to You';put b/b/a 'Dear SAS'/b;run;
\$\endgroup\$
1
\$\begingroup\$

Lua - 72 bytes

Straightforward, but none of the other Lua programs work this way.

a,b,c='Happy Birthday ','to You\n','Dear Lua\n'io.write(a,b,a,b,a,c,a,b)
\$\endgroup\$
1 2 3
4
5
7

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.