text:
Unscramble those case-(very)-sensitive strings
Goal
This is a simple challenge. Your goal is to unscramble a string by swapping each letter with the next letter of the same case, while leaving non-letter characters unchanged.

Step by step explanation

The first character is a E. We look for the next letter in upper case: it's a C. We swap these characters, which leads to CdoE!.

We advance to the next character: this is a d. We look for the next letter in lower case: it's a o. We swap these characters, which leads to CodE!.

We advance to the next character: this is the d that we've just moved here. We ignore it, because it has already been processed.

We advance to the next character: this is the E that was moved here at step #1. We ignore it, because it has already been processed.

We advance to the next character: this is a !. We ignore it, because it's not a letter.

Rules

You can assume that the input string is made exclusively of printable ASCII characters, in the range 32 - 126.

You may write either a full program or a function, which either prints or returns the result.

If the input string contains an odd number of letters, the last remaining letter can't be swapped with another one and should remain in place, no matter its case. The same logic applies if the string contains an even number of letters, but an odd number of uppercase letters and an odd number of lowercase letters.

This is code-golf, so the shortest answer in bytes wins. Standard loopholes are forbidden.

Test cases
Input : lLEhW OroLd!
Output: hELlO WorLd!

Input : rpGOZmaimgn uplRzse naC DEoO LdGf
Output: prOGRamming puzZles anD COdE GoLf

Input : eIt uqHKC RBWOO xNf ujPMO SzRE HTL EOvd yAg
Output: tHe quICK BROWN fOx juMPS OvER THE LAzy dOg

Input : NraWgCi: Nsas-eNEiTIsev rNsiTG!!
Output: WarNiNg: Case-sENsITive sTriNG!!

Not-so-random test cases:
Input : (^_^)
Output: (^_^)

Input : AWCTY HUOS RETP
Output: WATCH YOUR STEP

Input : hwn oeesd acsp nawyya
Output: who needs caps anyway

Input : SpMycaeIesKyBorekn
Output: MySpaceKeyIsBroken

Input : D's mroyr, Ivam. I'e faardi I act'n od htta.
Output: I'm sorry, Dave. I'm afraid I can't do that.

I assume a similar comment holds if the input contains an even number of letters, but an odd number of uppercase letters and an odd number of lowercase letters.

This is a really clever challenge ... I also like the fact that test cases can be made by typing in a lowercase string, randomly changing some of the letters to uppercase, and then running the exact same program that solves the problem!

@GregMartin I found out that the problem is its own inverse because when trying a test case I accidentally typed in the output instead of the input :-)

I think you should include test cases with more than one non-letter ASCII character ... I think some implementations could accidentally switch them with each other, when that's not supposed to happen.

The tests cases should probably include a string without uppercase letters and a string without any letters at all.

Note to self: Read more carefully... I wrote a behemoth that replaced the first x-case letter with the last, not the next.

Jelly, 21 20 19 18 bytes
s2UF,
nŒlTÇyJịŒsµ⁺

Try it online!
How it works
nŒlTÇyJịŒsµ⁺  Main link. Argument: s (string)

 Œl           Convert to lowercase.
n             Test for inequality.
   T          Truth; yield all indices of 1's.
    Ç         Call the helper link. Yields [A, B] (pair of lists).
      J       Indices; yield I := [1, ..., len(s)].
     y        Translate; replace the integers of I that occur in A with the
              corresponding integers in B.
        Œs    Swapcase; yield s with swapped case.
       ị      Use the translated index list to index into s with swapped case.
          µ   Combine all links to the left into a chain.
           ⁺   Duplicate the chain, executing it twice.

s2UF,         Helper link. Argument: J (list of indices)

s2            Split J into pairs. If the length is odd, the last list will be
              a singleton list.
  U           Upend; reverse each pair. This is a no-op for singletons lists.
   F          Flatten, concatenating the pairs.
    ,          Pair the previous result with J.

Retina, 53 bytes
Not really clever, but a clean and quite readable solution
([a-z])(.*?)([a-z])
$3$2$1
([A-Z])(.*?)([A-Z])
$3$2$1

Try it online!

MATL, 22 bytes
2:"tttk<f2etAZ))P5M(Yo

Try it online! Or verify all test cases.
How it works
2:"       % Do the following twice
  ttt     %   Input string (implicit). Push three more copies
  k       %   Convert to lowercase
  <f      %   Indices of characters that had their code point increased by
          %   the lowercase conversion, i.e. that were uppercase letters
  2e      %   Convert to 2-row matrix. This pads a zero in the lower-right
          %   corner if necessary
  tAZ)    %   Keep only columns that don't contain zeros. Thus if there
          %   was a character that can't be swapped it will be ignored
  )       %   Get 2-row matrix of characters at those positions
  P       %   Flip vertically. This does the swapping
  5M      %   Push matrix of original indices again
  (       %   Write the swapped characters onto their original positions
  Yo      %   Change case. In the first iteration, this prepares the
          %   string so the second iteration will process the letters that
          %   were originally lowercase. In the second iteration, it
          %   undoes the change of case
          % End (implicit)
          % Display (implicit)

ES6, 185 95 bytes
i=>(o=[...i]).map((c,j)=>/[a-z]/i.test(c)?o[e=c>"Z"]=1/(b=o[e])?o[o[j]=o[b],b]=c:j:0)&&o.join``

Solution severely shortened with the help of @Neil, @Arnauld and @edc65
Explanation

f = i =>
  // Get array of characters from input string
  (o = [...i])
    .map((c, j) =>
      // Check if it's a text character, otherwise skip it
      /[a-z]/i.test(c) ?
        // Get last character position for case
        // merged with setting a variable for if the character is lowercase
        // merged with storing the current case character position,
        // under properties on the array (with keys "true" or "false")
        o[e = c>"Z"] =
          // Check if there exists a character position to switch with
          // merged with storing the current position for quick access
          1/(b=o[e]) ?
            // This statement will end up returning the Array subset,
            // which will be falsy in the above conditional since (1/[])==false
            o[
              // Switch left character to the right
              o[j]=o[b]
            // Switch right character to the left
            ,b]=c :
            // No character exists for case, so return current character position
            j
         // It was not a text character, so do nothing
         :0
      )
  // Join array and return as result
  && o.join``;

`lLEhW OroLd!
NraWgCi: Nsas-eNEiTIsev rNsiTG!!
rpGOZmaimgn uplRzse naC DEoO LdGf
eIt uqHKC RBWOO xNf ujPMO SzRE HTL EOvd yAg
(^_^)
AWCTY HUOS RETP
hwn oeesd acsp nawyya
SpMycaeIesKyBorekn
D's mroyr, Ivam. I'e faardi I act'n od htta`
  .split`\n`
  .map(testCase => console.log(f(testCase)));

6 bytes, the enclosing parens are redundant when we remove the second statement :) Nice.

Please ignore my last comment. Here's the 99: /[a-z]/i.test(c)?o[e=c>"Z"]=1/(b=o[e])?[o[b],o[j]]=[c,o[b]]:j:0

[o[b],o[j]]=[c,o[b]] could be o[o[j]=o[b],b]=c

The real masterstroke here is using true and false as indexes for an array

Thanks guys, down to 95 now. It starts becoming really hard to document the solution in a way that makes sense. XD @edc65 they're stored as properties on the array object, not indexes. Yeah Arnauld figured out that they were being stored on the character array, but the reuse of the object was more of a lucky accident I think which came from a separate suggestion. Initially it was stored on a separate object which of course was completely unnecessary for the scope of the challenge.

Bash + Unix utilities, 77 62 57 56 54 bytes
sed -r "s/([$1)([^$1*)([$1)/\3\2\1/g"||$0 a-z]|$0 A-Z]

Input in stdin.
Output in stdout.
(In this last version, stderr happens to be written to also, but PPCG consensus seems to be that that's OK -- stderr is simply ignored.)
Edit 1: Thanks to @Dennis for 15 bytes! Improvements: (a) Taking input via stdin; (b) combining 2 sed scripts into one; and (c) replacing tr with substitution via bash parameter expansion; (b) and (c) disappeared in Edit 2.
Edit 2: Shorter by 5 additional bytes. Used a function call to replace both (b) and (c) in Edit 1.
Edit 3: One more byte -- passed ] as part of the function arguments.
Edit 4: Replaced the two function calls with calls to the program itself when it has no arguments.
Testbed and sample output:
for x in 'lLEhW OroLd!' 'rpGOZmaimgn uplRzse naC DEoO LdGf' 'eIt uqHKC RBWOO xNf ujPMO SzRE HTL EOvd yAg' 'NraWgCi: Nsas-eNEiTIsev rNsiTG!!' '(^_^)' 'AWCTY HUOS RETP' 'hwn oeesd acsp nawyya' 'SpMycaeIesKyBorekn' "D's mroyr, Ivam. I'e faardi I act'n od htta."; do ./swapping <<<"$x" 2>/dev/null; done

hELlO WorLd!
prOGRamming puzZles anD COdE GoLf
tHe quICK BROWN fOx juMPS OvER THE LAzy dOg
WarNiNg: Case-sENsITive sTriNG!!
(^_^)
WATCH YOUR STEP
who needs caps anyway
MySpaceKeyIsBroken
I'm sorry, Dave. I'm afraid I can't do that.

Python, 82 bytes
lambda s:S(r.lower(),t,S(r,t,s))
import re
S=re.sub
r='([A-Z])(.*?)'*2
t=r'\3\2\1'

Try it online!

how does it work? is the lambda even called?

The lambda is the actual (function) submission. Everything else is just accompanying code that has to be executed before the lambda is called.

QBasic, 229 bytes
LINE INPUT s$
FOR i=1TO LEN(s$)
c$=MID$(s$,i,1)
IF"@"<c$AND"[">c$THEN
IF u THEN MID$(s$,u,1)=c$:MID$(s$,i,1)=u$
u=-i*(u=0)
u$=c$
ELSEIF"`"<c$AND"{">c$THEN
IF l THEN MID$(s$,l,1)=c$:MID$(s$,i,1)=l$
l=-i*(l=0)
l$=c$
END IF
NEXT
?s$

Strategy
We loop through the input string. When we encounter an uppercase letter, we store it and its position. The second time we encounter an uppercase letter, we use those stored values to swap it with the previous one. Same for lowercase.
(I was about to post a rather longer version that used an array, because I thought that QBasic strings were immutable. Then I stumbled across the fact that MID$(strng$, index, length) = replacement$ works just fine. Live and learn.)
Ungolfed + commented
LINE INPUT text$

FOR i = 1 TO LEN(text$)
  char$ = MID$(text$, i, 1)
  IF "A" <= char$ AND "Z" >= char$ THEN
    ' Uppercase
    IF upperIndex = 0 THEN
      ' This is the first of a pair of uppercase letters
      ' Store the letter and its index for later
      upperLetter$ = char$
      upperIndex = i
    ELSE
      ' This is the second of a pair of uppercase letters
      ' Put it at the position of the previous uppercase letter
      ' and put that letter at this letter's position
      MID$(text$, upperIndex, 1) = char$
      MID$(text$, i, 1) = upperLetter$
      upperIndex = 0
    END IF
  ELSEIF "a" <= char$ AND "z" >= char$ THEN
    ' Lowercase
    IF lowerIndex = 0 THEN
      ' This is the first of a pair of lowercase letters
      ' Store the letter and its index for later
      lowerLetter$ = char$
      lowerIndex = i
    ELSE
      ' This is the second of a pair of lowercase letters
      ' Put it at the position of the previous lowercase letter
      ' and put that letter at this letter's position
      MID$(text$, lowerIndex, 1) = char$
      MID$(text$, i, 1) = lowerLetter$
      lowerIndex = 0
    END IF
  END IF
NEXT i

PRINT text$

Qbasic, 436 408 bytes
LINE INPUT a$:b=len(a$):FOR a=1TO b:t$=MID$(a$,a,1)
IF"@"<t$AND"[">t$THEN
b$=b$+"U":u$=u$+t$
ELSEIF"`"<t$AND"{">t$THEN
b$=b$+"L":l$=l$+t$
ELSE b$=b$+t$
END IF:NEXT
FOR x=1TO b STEP 2:g$=g$+MID$(u$,x+1,1)+MID$(u$,x,1):h$=h$+MID$(l$,x+1,1)+MID$(l$,x,1):NEXT
FOR x=1TO b:t$=MID$(b$,x,1)
IF"U"=t$THEN
u=u+1:z$=z$+MID$(g$,u,1)
ELSEIF"L"=t$THEN l=l+1:z$=z$+MID$(h$,l,1)
ELSE z$=z$+t$
END IF:NEXT:?z$

Saved one byte thanks to DLosc. Saved several more by changing handling of non-letter chars.
This basically consists of three parts:

Splitting the input into 3 strings (Uppercase, Lowercase, and a map (also holding the other chars))
Flipping the uppercase and lowercase letters
Using the map to (re)construct the output.

A more detailed explanation (note that this is of an earlier version of the code, but the principle still applies):
' --- Part I: Reading the input
LINE INPUT a$
'This FOR loop takes one character at a time
b=len(a$):FOR a=1TO b
' And checks in what category the character belongs
t$=MID$(a$,a,1):SELECT CASE t$
' For each group, char t$ is added to that group (u$ for uppercase,
' l$ for lowercase. The map in b$ is updated with a U or L on this index,
' or with the non-letter char t$.
CASE"A"TO"Z":b$=b$+"U":u$=u$+t$
CASE"a"TO"z":b$=b$+"L":l$=l$+t$
CASE ELSE:b$=b$+t$
END SELECT:NEXT

' --- Part II: Swapping within case-groups
' Loop through u$ and l$ twp chars at a time, and add those chunks in reverse order
' to g$ and h$. Because mid$ doesn't fail past the end of a string (but returns ""),
' this automatically compensates for odd-length groups.
FOR x=1TO b STEP 2:g$=g$+MID$(u$,x+1,1)+MID$(u$,x,1):h$=h$+MID$(l$,x+1,1)+MID$(l$,x,1):NEXT

' --- Part III: Read the map to put it all back together
FOR x=1TO b:t$=MID$(b$,x,1)
' See what group was in this spot, then read the next char from the flipped string.
' This keeps an index on those strings for the next lookup.
IF t$="U"THEN
u=u+1:z$=z$+MID$(g$,u,1)
ELSEIF t$="L"THEN l=l+1:z$=z$+MID$(h$,l,1)
' The map contains a non-letter char, just drop that in
ELSE z$=z$+t$
' And finally,display the end result.
END IF:NEXT:?z$

C++11 (GCC), 154 149 bytes
#include<algorithm>
[](std::string s){int*p,u,l=u=-1;for(auto&c:s)(c|32)-97<26U?p=&(c&32?u:l),~*p?(std::swap(c,s[*p]),*p=-1):*p=&c-&s[0]:0;return s;}

You should either also #include<string> or switch to C++14 and declare a generic lambda [](auto s) and assume s to be of std::string. Also, declaring [](auto&s) saves you from returning the string as modifying input arguments to serve as output is allowed.

PHP, 108 93 83 bytes
<?=preg_replace([$a="/([a-z])([^a-z]*)([a-z])/",strtoupper($a)],"$3$2$1",$argv[1]);

Previous version (93 bytes)
<?=preg_replace(["/([a-z])([^a-z]*)([a-z])/","/([A-Z])([^A-Z]*)([A-Z])/"],"$3$2$1",$argv[1]);

Thanks to @user59178 for reminding me that preg_replace() can take arrays of strings as arguments.

The original answer (108 bytes)
$f=preg_replace;echo$f("/([a-z])([^a-z]*)([a-z])/",$r="$3$2$1",
$f("/([A-Z])([^A-Z]*)([A-Z])/",$r,$argv[1]));

The code is wrapped here to fit the available space.
It can be executed from the command line:
$ php -d error_reporting=0 -r '$f=preg_replace;echo$f("/([a-z])([^a-z]*)([a-z])/",$r="$3$2$1",$f("/([A-Z])([^A-Z]*)([A-Z])/",$r,$argv[1]));' 'lLEhW OroLd!'

A 1-byte shorter version is possible on PHP 7 by squeezing the assignment of $f inside its first call:
echo($f=preg_replace)("/([a-z])([^a-z]*)([a-z])/",$r="$3$2$1",
$f("/([A-Z])([^A-Z]*)([A-Z])/",$r,$argv[1]));

Both solutions, with test cases and ungolfed versions can be found on Github.

preg_replace can take an array of replacements to do so you only need one call. In addition it's shorter to use <?= than echo. With these it's simple to get your answer down to 93 bytes.

You are right about preg_replace(). I forgot about it. I don't like <?= (in my opinion <? is not part of the language, it is just a marker) and I like to write short one-line programs that can be executed from the command line using php -r. But for the purpose of code golf you are right again. I can save 1 byte using <?=.

Perl 5, 48 + 1 (-p) = 49 bytes
for$p(qw/([a-z]) ([A-Z])/){s/$p(.*?)$p/$3$2$1/g}

Try it online!

Ruby, 81 bytes
puts f=->(i,s){i.gsub /([#{s})([^#{s}*)([#{s})/,'\3\2\1'}[f[$*[0],'a-z]'],'A-Z]']

JavaScript (ES6), 80 bytes
Based on Leo's Retina answer.
s=>eval("s"+(r=".replace(/([A-Z])([^A-Z]*)([A-Z])/g,'$3$2$1')")+r.toLowerCase())

This works because the only uppercase characters in the code .replace(/([A-Z])([^A-Z]*)([A-Z])/g,'$3$2$1') are A and Z, which are used to describe the character ranges. This is precisely what we need to transform into lowercase in order to process the second pass.
Test cases

let f =

s=>eval("s"+(r=".replace(/([A-Z])([^A-Z]*)([A-Z])/g,'$3$2$1')")+r.toLowerCase())

console.log(f("lLEhW OroLd!"));
console.log(f("rpGOZmaimgn uplRzse naC DEoO LdGf"));
console.log(f("eIt uqHKC RBWOO xNf ujPMO SzRE HTL EOvd yAg"));
console.log(f("NraWgCi: Nsas-eNEiTIsev rNsiTG!!"));
console.log(f("(^_^)"));
console.log(f("AWCTY HUOS RETP"));
console.log(f("hwn oeesd acsp nawyya"));
console.log(f("SpMycaeIesKyBorekn"));
console.log(f("D's mroyr, Ivam. I'e faardi I act'n od htta."));

Actually, it turns out to be very similar to this Python answer by Dennis.

ES6 155 - 195 bytes
I know there's already a better answer, but I wanted to try without regex.
This one works on punctuation too, but that seems to violate the (^_^) test. In that case I have another c() function, given below.
f=(s)=>{d={};s=[...s];for(i in s){b=s[i];for(j in s)if(i<j&!d[i]&c(s[j])==c(b)){d[j]=1;s[i]=s[j];s[j]=b;break}}return s.join('')}
c=c=>~(c.charCodeAt()/32)

f("M I'o DaG") //> I'M a GoD
f("(^_^)")     //> )_^^(

c=c=>((c!=c.toUpperCase())<<1|c!=c.toLowerCase())||c.charCodeAt()

f("M I'o DaG") //> I'M a GoD
f("(^_^)")     //> (^_^)

Explanation
f=(s)=>{
    d={};        //list of indexes already swapped
    s=[...s];        //string to array, stolen from above ES6 answer
    for(i in s){
        b=s[i];        //keep a note of what we are swapping
        for(j in s)        //iterate over the array again
            if( i<j & !d[i] & c(s[j])==c(b) ){
                        //only pay attention after we pass i'th
                        //only swap if this char hasn't been swapped
                        //only swap if both chars in same 'category'
                d[j]=1;        //note that the latter char has been swapped
                s[i]=s[j];
                s[j]=b;
                break        //avoid swapping on the same 'i' twice
            }
    }
    return s.join('')        //return as string
}

Perl 6, 56 bytes
{for "A".."Z","a".."z" ->@c {s:g/(@c)(.*?)(@c)/$2$1$0/}}

Takes a string variable as an argument, and modifies it in-place so that after calling the lambda the variable contains the result.
Longer than it would be in Perl, because:

The new regex syntax is more verbose, e.g. writing out the character classes would look like <[A..Z]> instead of [A-Z].
Regexes are first-class source code parsed at compile time, and a string can only be interpolated into them at run-time if it consists of a self-contained subregex (i.e. you can't interpolate a string into a character class).
Explict EVAL, which would allow more flexibility, requires the golf-unfriendly use MONKEY-SEE-NO-EVAL; pragma.

On the plus side, an array in a @ variable can be referenced directly in a regex, and is treated as an alternation.

Perl 6, 65 bytes
{reduce ->$_,@c {S:g/(@c)(.*?)(@c)/$2$1$0/},$_,"A".."Z","a".."z"}

Functional version (outputs the result as the return value of the lambda).

R, 343 Bytes
Terribly clumsy R solution:
f <- function(x) {
        y=unlist(strsplit(x,""))
        z=data.frame(l=ifelse(y %in% letters,0,ifelse(y %in% LETTERS,1,2)),s=y)
        l <- list(which(z$l==0),which(z$l==1))
        v <- unlist(l)
        for(j in 1:2) for (i in seq(1,ifelse(length(l[[j]])%%2==1,length(l[[j]])-2,length(l[[j]])-1),2)) l[[j]][i:(i+1)] <- rev(l[[j]][i:(i+1)])
        z[v,] <- z[unlist(l),]
        return(z$s)
    }

f("D's mroyr, Ivam. I'e faardi I act'n od htta.")

# [1] I ' m   s o r r y ,   D a v e .   I ' m   a f r a i d   I   c a n ' t   d o   t h a t .

Mathematica, 96 bytes
s[#,r="([a-z])(.*?)([a-z])"]~(s=StringReplace[#,RegularExpression@#2->"$3$2$1"]&)~ToUpperCase@r&

A port of Leo's Retina answer, which uses regular expressions.

I'm honestly surprised that mathematica doesn't have a builtin for that, I mean, if "When's Easter sunday", "When's the sunset" and "what is the shape of france" get builtins, this one should too!

Python 2, 124 bytes
s=input();u=str.isupper
exec"r='';i=0\nfor c in s:r+=c[u(c):]or filter(u,s+s[::-1])[i^1];i+=u(c)\ns=r.swapcase();"*2
print s

Not as short as my regex-based solution, but I think it's still interesting.
Try it online!

Python 2, 181 bytes
Much longer than it should be but anyway:
def F(s):
 for l in[i for i,c in enumerate(s)if c.isupper()],[i for i,c in enumerate(s)if c.islower()]:
  for a,b in zip(l[0::2],l[1::2]):s=s[:a]+s[b]+s[a+1:b]+s[a]+s[b+1:]
 print s

This first creates two lists: one of the indices of the uppercase characters and one for the lowercase characters. Each of these lists is looped through in pairs of indices, and the characters at those indices are switched.
I'll golf this down tomorrow, but for now it's time to sleep.

Bean, 83 bytes
Hexdump:
00000000 26 53 d0 80 d3 d0 80 a0 5d 20 80 0a a1 81 81 00  &SÐ.ÓÐ. ] ..¡...
00000010 23 81 01 20 80 0a a1 81 81 02 23 81 01 a8 db c1  #.. ..¡...#..¨ÛÁ
00000020 ad da dd a9 a8 db de c1 ad da dd aa bf a9 a8 db  .ÚÝ©¨ÛÞÁ.ÚÝª¿©¨Û
00000030 c1 ad da dd 29 a4 b3 a4 b2 a4 31 a8 db e1 ad fa  Á.ÚÝ)¤³¤²¤1¨Ûá.ú
00000040 dd a9 a8 db de e1 ad fa dd aa bf a9 a8 db e1 ad  Ý©¨ÛÞá.úÝª¿©¨Ûá.
00000050 fa dd 29                                         úÝ)
00000053

Equivalent JavaScript:
a.replace(/([A-Z])([^A-Z]*?)([A-Z])/g,'$3$2$1').replace(/([a-z])([^a-z]*?)([a-z])/g,'$3$2$1')

Explanation:
Implicitly taking the first line of input unformatted as a (since newlines can't be part of scrambled string), and implicitly outputs unscrambled string by sequentially replacing uppercase, then lowercase pairs.
Try demo here.
Try test suite here.

AWK, 121 129 bytes
BEGIN{FS=OFS=""}{for(a=1;a<=NF;a++){if($a~/[A-Z]/?U>0?p=U+(U=0):0*(U=a):$a~/[a-z]/?L>0?p=L+(L=0):0*(L=a):0>0){t=$a;$a=$p;$p=t}}}1

Try it online! Note: Link has 8 extra bytes to allow multiline input
Usage is fairly typical, but does require a version of AWK that accepts an empty string as the field separator (most versions of gawk but I'm pretty sure the original AWK would fail :( )
It's very straightforward as it simply iterates over each character and checks if it's found one of that case before.  If so, it swaps the characters and resets the checked index. On the learning side of things, I'd never used an assignment statement within an assignment statement in AWK before.  For some reason it had never come up. :)
I might be able to shave a couple of bytes by saying to assign OFS and FS outside a BEGIN block via command-line assignment or similar, but it's "cleaner" this way.
Adding the TIO link showed me that I had a transcription error that required 8 bytes to fix :( (I left out 0*(U=a):)

Pip, 28 bytes
Y[XLXU]aRy.`.*?`.y{Sa@0a@va}

Takes input as a command-line argument. Try it online!
Explanation
This is a regex solution, using the builtin regex variables XL (lowercase letters, `[a-z]`) and XU (uppercase letters, `[A-Z]`).
                              a is 1st cmdline arg; v is -1 (implicit)
Y[XLXU]                       Yank a list containing XL and XU into y
         y.`.*?`.y            Concatenate y, `.*?`, and y itemwise, giving this list:
                              [`[a-z].*?[a-z]`; `[A-Z].*?[A-Z]`]
       aR                     In a, replace matches of each regex in that list...
                  {        }  ... using this callback function:
                   Sa@0a@v     Swap the 0th and -1st characters of the match
                          a    and return the resulting string
                              Print (implicit)

When the second argument to R is a list, the replacements are performed in series; thus, the lowercase replacement and the uppercase replacement don't interfere with each other.

C (gcc), 212 206 205 203 bytes

Thanks to ceilingcat for golfing six seven nine bytes.

#define I(a,b)if(S[j=i]/a&b/S[i]){for(;S[++j]<a|S[j]>b;);j<l?s[i]=S[j],s[j]=S[i]:0;}
i,j,l;f(char*S){char*s=calloc(l=-~strlen(S),1);for(i=~0;++i<strlen(S);)if(!s[i]){s[i]=S[i];I(65,90)I(97,'z')}puts(s);}

Try it online!

@ceilingcat Thank you.

@ceilingcat Thank you.

@ceilingcat Thank you.

Stax, 18 bytes
âß:}\]ó☺æ■jφ╛jz/Φi

Run and debug it
The general approach is regex-based.

Two times do:
Find all matches for [a-z].*?[a-z].
Swap the first and last character in matches.
Invert case.

R, 223 163 bytes 148 bytes
EDIT: -60 bytes by implementing a for loop
EDIT: -15 bytes from Giuseppe
u=utf8ToInt(scan(,''));for(i in c(65,97)){l=which(u%in%i:(i+25));x=sum(l|1)%/%2;u[l[1:(x*2)]]=u[c(matrix(l,2)[2:1,1:x])]};cat(intToUtf8(u,T),sep="")

Try it online!
Works by testing if character is a lowercase or uppercase, places them in a matrix, inverts the matrix to extract the values in a swapped format. Then output with cat. Try it online struggles with scan(,'') if the code is more than one line, hence the semicolons throughout the single line of code.

I get 168 on your link, but this golf is 163

And this brings it to 162.

this probably works; the x fiddling is the clever bit, but getting rid of m=matrix was 4 bytes as well.

What about the scan(,'') problem? And reducing the "lLEhW OroLd!" in TIO to scan(,'') or some other way to get input?

Obviously, in R, one can easily run the lines one by one, giving input as requested, but running it as a chunk - like in TIO - confuses the scan(,'')

Use ; instead of line breaks.

The semicolon doesn't seem to fix the scan(,'') problem. If the following link worked, we'd be down to 149. https://tio.run/##Dc5NC8IgGADg@37FGsjet4SY0NfCY4dg0GXRQTwMa0xwGk5JqH776vkFj5/nyGPo96072wCT6izQskQ8Zr3zoHNtcwXbDT3sEN@GvwatBohEW6Jr0Cu2QcwSn@II5lMhWROWRWFEVUNaMpSSR6Fg7ILXCQxlKFhd0apOEuU3U10AbUPrrv8BRNoinR5PXhQ4F6Y5Dbf84l1zXxTzDw

You missed a couple: https://tio.run/##Dc5NC4IwGADgv2LC8H1rEA76muzYIRC6GB3Eg6zEwdxibjSofvvy/hwel1IQwQ/Hxl6Mh1n2BmhRIFaDdaAyZTIJ@x09HRA/WrxHJUcIRBmiOKgN2y0yijlMoL8lki1hVWh1W3KIa4ZdJ0IrYeq9UxE0ZdgyXtKSxw67XyV7D8r4xt6WAATaIJ2fL5HnmHJdn8d7dnW2fqzy9Ac

05AB1E, 26 23 bytes
2FÐlø€Ë≠āsƶ0KD2ôí˜‡<è.š

I/O as a list of characters.
Try it online or verify all test cases.
Explanation:
2F                # Loop 2 times:
  Ð               #  Triplicate the current character-list
                  #  (which will use the implicit input-list in the first iteration)
   l              #  Lowercase all letters of the top copy
    ø             #  Zip/transpose the top two lists; pairing them together, and swapping
                  #  rows/columns
     €Ë≠          #  Check for each pair whether they're NOT the same
                  #  (so uppercase characters that have now become lowercase)
  ā               #  Push a list in the range [1, length] (without popping)
   s              #  Swap so the mapped list is at the top again
    ƶ             #  Multiply each 1/0 by its 1-based index
     0K           #  Remove all 0s
       D          #  Duplicate this list of 1-based indices
        2ô        #  Split it into parts of size 2
          í       #  Reverse each part
           ˜      #  Flatten the list of swapped indices
            ‡     #  Transliterate the indices with the swapped indices in [1, length]
             <    #  Decrease each by 1 (because 05AB1E uses 0-based indexing)
              è   #  Index them into the current character-list
               .š #  And swap all cases (lowercase to uppercase, and vice-versa)
                  # (after the loop, the resulting character-list is output implicitly)

Java 7, 117 bytes
String c(String s){String x="([a-z])(.*?)([a-z])",y="$3$2$1";return s.replaceAll(x,y).replaceAll(x.toUpperCase(),y);}

EDIT: Just noticed I have a similar answer as @Leo's Retina answer, even though I've thought about it independently..
Ungolfed:
String c(final String s) {
  String x = "([a-z])(.*?)([a-z])",
         y = "$3$2$1";
  return s.replaceAll(x, y).replaceAll(x.toUpperCase(), y);
}

Test code:
Try it here.
class M{
  static String c(String s){String x="([a-z])(.*?)([a-z])",y="$3$2$1";return s.replaceAll(x,y).replaceAll(x.toUpperCase(),y);}

  public static void main(String[] a){
    System.out.println(c("lLEhW OroLd!"));
    System.out.println(c("rpGOZmaimgn uplRzse naC DEoO LdGf"));
    System.out.println(c("eIt uqHKC RBWOO xNf ujPMO SzRE HTL EOvd yAg"));
    System.out.println(c("NraWgCi: Nsas-eNEiTIsev rNsiTG!!"));
    System.out.println(c("(^_^)"));
    System.out.println(c("AWCTY HUOS RETP"));
    System.out.println(c("hwn oeesd acsp nawyya"));
    System.out.println(c("SpMycaeIesKyBorekn"));
    System.out.println(c("D's mroyr, Ivam. I'e faardi I act'n od htta."));
  }
}

Output:
hELlO WorLd!
prOGRamming puzZles anD COdE GoLf
tHe quICK BROWN fOx juMPS OvER THE LAzy dOg
WarNiNg: Case-sENsITive sTriNG!!
(^_^)
WATCH YOUR STEP
who needs caps anyway
MySpaceKeyIsBroken
I'm sorry, Dave. I'm afraid I can't do that.


text:
Arbitrary PEMDAS
Scrolling through social media, one might encounter something like this:

We can see that, following PEMDAS order of operations, the answer is clearly 11 9.
For the sake of this challenge, PEMDAS means that multiplication will occur before division, so a/b*c = a/(b*c), not (a/b)*c. The same goes for addition and subtraction. For example, using PEMDAS, 1-2+3 = -4, but using PEMDSA, 1-2+3 = 2.
However, the answer quickly changes if we use some other order of operations, say PAMDES: now the answer is 12.
The challenge
Given an expression and an order of operations, output the value it equals.
Input
The input will contain two parts: the expression and the order of operations.
The expression will contain only [0-9] ( ) ^ * / + -. This means that it will contain only integers; however, you may not use integer division, so 4/3=1.33 (round to at least two decimal places), not 1.
The order of operations may be taken in any reasonable format. For example, you may take a string array of operations (ex. ["()", "^", ... ]), or something like PEMDAS. Parenthesis will always have the highest priority, and will therefore always come first in the input.
Output
The inputted expression evaluated and rounded to at least two decimal places.
This is code-golf, so shortest code in bytes wins!
Test cases
PEMDAS 4*3-2+1             =  9
PDEMAS 2*4^3+2             =  130
PMDASE 17^2-1*2            =  1
PSEMAD 32*14/15-12+5^3+1/2 =  1.736
PEMDAS 6/2*(1+2)            =  1
PEDMAS 6/2*(1+2)            =  9
PDMSEA 2*(1*13+4)^3        =  39304

1. No joke: many thought the answer was 1.
2. Here we are using the "for the sake of this challenge" PEMDAS rules.

Will concatenation ever be used to indicate multiplication, or will there be an explicit * every time? (Note that this is precisely the issue that caused people to think that the answer to the original puzzle is 9, even though it really is 1: concatenation-notated multiplication has a higher precedence than division in practice.)

@GregMartin, no, there will never be any concatenation

Can the output be left as an exact fraction, rather than rounded off as a decimal?

@GregMartin, it doesn't have to be rounded

Another question! Can we take the expression in with spaces surrounding operators, like 17 ^ 2 - 1 * 2 instead of 17^2-1*2?

@GregMartin, any reasonable input works.

I cannot understand for the life of me how the answer to the top equation is 9 if multiplication comes before division. Maybe I'll read the challenge again when I'm not so tired and understand it....

@ETHproductions, the answer is 9 under normal PEMDAS, where for * and / it is whichever comes first from left to right (same for + and -). Normally, * and / have equal precedence. However, in this challenge, the precedence is decreasing from left to right in the acronym/input.

http://codegolf.stackexchange.com/q/61463/21348 related or duplicate?

It's a duplicate, I can simply post my old answer to that challenge and it correctly answer this one

@Dopapp, Oh, I see now, thanks for the explanation. I guess I was wrong in thinking that multiplication by juxtaposition came before regular muliplication and division.

@ETHproductions: when kids are taught PEMDAS, they're taught that multiplication and division have the same predecence and should be evaluated left to right. However, as a practicing mathematician, I can report that this is oversimplistic: in practice, multiplication-by-juxtaposition does have higher precedence than division. Expressions like 1/3x and a/b(c-d) are never interpreted as (1/3)x or (a/b)(c-d). The ÷ symbol is not often used outside of school math, but even then, no practicing mathematician would look at 6÷2(1+2) and interpret it as (6÷2)(1+2).

@GregMartin Hmm, that's what I originally thought. So the example given is just a "following the letter of the law" kind of thing.... That makes more sense. Thanks!

@ETHproductions, originally I was going to write "follow the letters to the letter", but that sounded confusing when I said it out loud.

This reminds me of yesterday when I was writing an arithmetic-calculating function and struggling to get the order of operations right... At one point, 1+0!*7**2 would give 50, but 1+0!*(7**2) would give 98. It took me forever to figure out why :P (I don't remember the reason, but it had something to do with 1+0! being calculated first in the latter case)

Maxima, 61 67 bytes
f(O,E):=(for i:1 thru 5 do infix(O[7-i],i*20,i*20),eval_string(E));

A function that takes operators as a list of strings and the expression and returns the result.
Try it online!
Example:
f(["()","^","*","/","+","-"],"4*3-2+1");

result: 9

That seems to have trouble with parens

@ChristianSievers Thanks, answer updated.

source: Stack Exchange

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

sort: votes


text:
Create a simple mancala game
Simple Mancala Game
Create a mancala game using as few bytes as possible.
The game
Mancala is a family of games where a player has a control over a set amount of pots filled with stones/seeds. The particular version which you should implement has a board with 14 pots, of which two are designated as scoring pots. At the start of the game the scoring pots are empty and each of the other pots contains 4 stones. On each player's turn they select one non-empty non-scoring pot, remove the stones from it, and starting with the next pot counter-clockwise they place one stone per pot, moving counterclockwise, until they have placed them all.
Unlike some other variants, there is no way to get a second turn. Once the stones from one pot have been redistributed, the play passes to the other play.
The game ends when all the stones are in the scoring pots, so that there is no valid move remaining.
The challenge
Implement a simple program to allow two players to play against each other at a shared computer. No AI is required.
For the purposes of input, the pots are labelled as shown:
(R1H1)[R1P6][R1P5][R1P4][R1P3][R1P2][R1P1]

[R2P1][R2P2][R2P3][R2P4][R2P5][R2P6](R2H1)

The scoring pots are (R1H1) and (R2H1).
The input will be a list of pots separated by a semicolon: e.g. R2P3;R2P1. These represent the moves in order from left to right. You may assume that each move is valid.
The output will be the number of stones in each pot after the input moves have been performed. The output need not use brackets in the same way as the diagram above or the examples below, but the pots must be distinguishable and the scoring pots should also be clearly distinguished from regular ones.
Worked example
The initial board position is
(0)[4][4][4][4][4][4]

[4][4][4][4][4][4](0)

Given input R2P3 the output should be
(0)[4][4][4][4][4][4]

[4][4][0][5][5][5](1)

placing the four stones from R2P3 in the first four pots working counter-clockwise from R2P3.
Given input R2P3;R2P1 the output should be
(0)[4][4][4][4][4][4]

[0][5][1][6][6][5](1)

Welcome to PPCG! It might be better to specify the output. Also you should put the [tag:code-golf] tag for these criterias.

I am voting to close this as unclear because as it currently stands it does not indicate input and output.  It also needs a winning criterion as suggested.

I revised it, should've helped

Please put Input/Output in codeblocks (backtick in each side or four spaces)

Also, the Sandbox might be able to help you.

I fixed it up, should be fine now, correct? Sorry, I'm quite obviously new to this.

@Sine_, it still contains much ambiguity. I highly recommend that you post your question in the Sandbox, where you can receive constructive feedback on your challenge ideas.

@Dopapp linking is [name](link), not (name)[link]

What's R and P in the input?

Row and Pot, edited to include so

Also, do we accept only one input for one move only?

Fixed for both the inquiries in chat and this one

How many pots? 2. How many seeds per pot at the start of the game? 3. How exactly does a turn work? It's not clear whether the side pots are in the normal sequence of dropping; and the version of mancala that I played years ago had the ability to get a second turn. 4. What determines the end of the game, and what determines who wins? 5. What's the numbering system used in your input example?

My revisions should have fixed this, but I'm not sure what you mean when you ask how a turn works.

This looks like an interesting challenge. My understanding is that we need to take all stones contained in the designated pot. However, this is not explicitly said anywhere. If you clarify this point and show the intermediate steps between R2P3 and R2P1, this should be much clearer. Also, you may want to be more flexible about the input format (accepting an array of moves instead of the semicolon-separated list, for instance).

The edits answered my questions, although I've rewritten it to try to separate out the game rules from the challenge. Before I vote to reopen I would like to ask (as Arnauld has) how flexible you are on the input format. Personally I would allow labelling the pots 0 to 13 or 1 to 14 in clockwise or anti-clockwise order, so long as the answer clearly specifies the convention followed. That allows people to focus on the game logic rather than on parsing the pot labels.

I suppose as long as the input is in some kind of sequence and not labeled randomly, it would be quite aright

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


text:
Create a Checkbox
Write a program that creates a two-state checkbox that people can interact with using a mouse.
Specifically, your program should achieve all of the following:

Have a 8×8 pixel (or larger if desired) region of the screen that is the clickable area of the checkbox. Henceforth this region is simply called the checkbox.

When the mouse cursor is moved within the checkbox and the default* mouse button is pressed, the checkbox should toggle states.
Checked becomes unchecked. Unchecked becomes checked.

The checkbox should not move when it is toggled.

In the checked state, the checkbox may be any colors.

In the unchecked state, the checkbox may be any colors as long as at least 16 pixels are visually distinct from the checked state.

In a single program instance, all checked states should be visually identical to one another and all unchecked states should be visually identical to one another.

Don't end the program until it's explicitly terminated (e.g. via exit button or Alt+F4), so a user can click the checkbox as much as they want.

*You may assume the default mouse button is always left click, but it's also fine to use the default as defined by mouse software or the OS, which may not actually be left click depending on the user.
Notes

It does not matter what is outside of your checkbox region.  It could just be the desktop. It could be a portion of a console that changes on every toggle.

It does not matter what state your checkbox starts in.

The checkbox region may have any dimensions at or above 8×8 pixels. It need not be square.

You may make minor allowances for settings that are out of your control such as console font size, browser zoom, monitor resolution, etc. As long your program works in a reasonable test setting it should be valid.

If your program opens a window, you may assume it has been dragged to an appropriate location on the screen if necessary (e.g. top left corner).

You may use markup languages such as HTML or other languages we usually don't consider as full-fledged programming languages.

Your checkbox must be be toggleable using the default mouse button. It's alright if it also toggles for other forms of input (e.g. right mouse button), with the exception of mouse motion. i.e. the state should not change if the mouse is merely moved within the checkbox.

Screenshots of your checkbox in action are highly encouraged!

Scoring
The shortest code in bytes wins.
Example
A canonical HTML example in 23 bytes.

<input type="checkbox">

For me in Google Chrome, this makes a 12×12 pixel checkbox and about 30 pixels clearly change between checked and unchecked states.
I make the allowance that browser zoom is at 100%.

Can the checkbox cover the entire screen?

@KritixiLithos Yes, that would be valid.Though note that you may, if desired, count a particular 8x8 region as the official checkbox, even if a larger region works.

@Helka Homba - is it allowed for an app to display other controls, aside the checkbox itself ?

Is it OK for the checkbox to toggle on other sorts of input? (For example, is a solution correct if the checkbox toggles on any sort of user input, regardless of whether it's a mouse click, a mouse movement, or a keypress? It'd toggle on a mouse click, but it'd toggle on other stimuli too.)

Would touching a touchscreen instead of using a mouse be acceptable?

When the mouse cursor is moved within the checkbox and the default mouse button is pressed Can we also toggle if the user clicks outside the checkbox or with another mouse button apart from the left one?

@zeppelin "It does not matter what is outside of your checkbox region. It could just be the desktop. It could be a portion of a console that changes on every toggle." So, as long as the checkbox is there, it doesn't matter what else is.

@ais523 / 12Me21 / Dennis it's ok if other forms of input, except for mouse-motion, (like keypress/touch/right click) also toggle the checkbox, whether inside the region or outside, as long as the default mouse button works to toggle the checkbox as well.

Finally a task where KV lang, or any lang that creates an instance from checkbox string just wins. But I fear there's some character/byte in some gibberish that does the same thing and if not, someone will write it just to solve this. :D

Can the checkbox display after another region is clicked? For example, the program runs, part of what displays is a button, upon clicking the button, a checkbox which satisfies all other conditions is visible.

@briantist No, I think the checkbox should show up right away

May we abuse external programs which has checkboxes?

"It does not matter what state your checkbox starts in." Does it matter if the initial state is distinct from the checked and the unchecked state?

Wait, does the checkbox have to be on the screen? 'cause we already have one on the keyboard!

Mathematica, 10 bytes
Checkbox[]

Assumes Mathematica's notebook environment.
The two states look like this:

Sure. Mathematica cheats again.

It's funny how the comment has more upvotes than the answer

@RudolfL.Jelínek it's funny how the answer has any upvotes at all...

HTML, 20 bytes
Don't know how valid this will be as an answer. HTML requires the tag to be closed to legally validate, but modern browsers will automatically close them so it's executable.

<input type=checkbox

I was looking at this as an option earlier (without quotes) but completely missed the closing >. +1 and valid IMHO.

On this site, languages are defined by their implementation, so this seems fine to me.

Thanks @JohnGowers , I've been wondering about the definition of how much abuse is acceptable.

I think you need to be more specific about which "modern browsers". It doesn't work in FF for me.

Bash, 67 55 50 35 32 31 bytes
:()(read -p$[i^=1]
›?9h -sn6
:)

The code contains a CR byte (first newline) and a CSI byte (small right angle bracket with the Windows-1252 encoding). It requires xterm (or equivalent) and the ISO-8859-1 encoding (or similar).
The code defines a function named :, which alternately displays a white 1 or 0 in a black rectangle. There are exactly 24 differing pixels with xterm's default settings. (proof)
For an older version that toggles the color of the entire terminal, check revision 10 of this answer.
Thanks to @ais523 for suggesting xterm, which saves 4 bytes!
How it works
:(...) creates a function named : that executes ....
The read command does the actual magic.

-p specifies an input prompt, which is printed to STDOUT.

$[i^=1] is an arithmetic expansion which XORs the variable i with 1. i may initially be unset; when this occurs, it will be treated as 0.
The carriage return places the cursor back at the beginning of the line.
›?9h captures the mouse in supported terminals. Each click will send six characters to the terminal, namely ←[Mbxy, where ← represents the ESC byte (0x1b). ←[ indicates an escape sequence, M the mouse, b the button (0x20 + the button number), x the x coordinate of the click (0x20 + coordinate), and y the y coordinate.
-sn6 makes read silent (the mouse input won't be echoed to STDERR) and stops after reading exactly 6 bytes. It saves the input in the REPLY variable, but we're not interested in the output it produces.

Finally, once read finishes (after exactly one mouse click), : recursively calls itself, entering an infinite loop.
Creation and invocation
$ echo $':()(read -p$[i^=1]\r\x9b?9h -sn6\n:);:' > checkbox.sh
$ xxd -c 17 -g 1 checkbox.sh
0000000: 3a 28 29 28 72 65 61 64 20 2d 70 24 5b 69 5e 3d 31  :()(read -p$[i^=1
0000011: 5d 0d 9b 3f 39 68 20 2d 73 6e 36 0a 3a 29 3b 3a 0a  ]..?9h -sn6.:);:.
$ LANG=en_US xterm -e bash checkbox.sh

Output

I was working on a similar solution to this myself (although in a different language, forcing me to give up because I couldn't find a way to take input without a newline). A likely improvement: change 1000h to 9h (the difference is that 1000h handles both mouse press and release, and 9h handles only mouse release). This might or might not need changes elsewhere in the code.

@ais523 I tried that, but at least my terminal emulator (Konsole) doesn't seem to support it. Do you know one that does?

gnome-terminal seems to work, that's what I was using for testing (edit: but I don't think it supports a 1-byte CSI). xterm should also work and might be easier to install if you have a KDE system. (I just tested this myself; it works with \x1b[ but not with \x9b for some reason, possibly related to my stty settings rather than to the terminal itself.)

@ais523 I do have xterm. I'll check when I'm back at my PC.

@ais523 xterm works like a charm!  I'll update asap, with a few more byte savings. To use the CSI byte, you have to set the terminal to Latin-1. LANG=en_US should do the trick. Gnome terminal might require additional settings.

@ais523 xterm saved 4 bytes. Thanks!

I love  how it becomes :) from :( by the end

GitHub Flavored Markdown - 6 bytes
- [ ]

(There is a trailing space)
In a gist :

Sure this matches the 2nd half of the 1st sentence, “Write a program that creates a two-state checkbox that people can interact with using a mouse.”?

Yes, if you paste it in a gist and create the gist (for "compilation") you will be able to interact with it.

Interesting. Thanks @Ax31. I never used gists.

I would not have expected "Github Flavoured Markdown".

HTML + JavaScript, 32 30 25 chars

0

this is implicit and can be removed. Also, innerHTML is shorter.

@Dennis, strange with this... Thank you.

+1 for not using the <input> element

Unix Shell (+x11-apps), 3 bytes
Disclaimer
The answer below is boring, borderline and "feels cheating" (at least to me).
Yet, it does not seem to violate any of the challenge rules "as written", or "default loopholes", so I'm posting it.
(If you can point a specific rule it breaks, please comment on !)
Golfed
xgc

The  xgc  program  demonstrates various features of the X graphics primitives.

The xgc screen is actually filled with various checkboxes:

and "sticky buttons" (which qualify as checkboxes, under this challenge rules):

Processing, 78 66 65 63 61 bytes
2 bytes saved thanks to @TuukkaX by using -a%2 instead of a%2*-1
2 bytes saved thanks to @TuukkaX by using a=-a
int a=1;void draw(){background(a);}void mousePressed(){a=-a;}

The checkbox alternates between being black and white.
Explanation
int a=1;                   //the variable that contains the state of the checkbox
void mousePressed(){a=-a;} //if the mouse is pressed, change the sign of a

Now there are many other alternatives like using an if-statement to process this, but then it gets weird and constantly changes the background while the mouse is being pressed. I first tried mouseButton, but then I would need more conditions and more code that will just end up much more verbose.
Now for mousePressed() to be called forever (otherwise it would just stop after the program has just started), we need a draw() function.
void draw(){               //loop infinitely
  background(a);           //set the sketch's background to -a%2
  //if a ==  1, the background colour is set to almost black
  //if a == -1, the background colour is set to white
}

A smaller checkbox would be 90 bytes (the checkbox is in the top left corner, so we can remove some mouse conditions):
int a=1;void draw(){fill(a);rect(0,0,8,8);}void mousePressed(){if(mouseX<9&mouseY<9)a=-1;}

Clever use of how Processing accept single integers as grayscale colours!

@FlipTack It seems that white can also be expressed as fill(-1)

I have an idea. Initialize a to 1 instead of 0. Change a++ to a=-a, which makes -a%2 just a. This will toggle a between 1 and -1. I don't know what color 1 produces though.

@TuukkaX Yup it works. color(1) produces #010101 which is very close to black

AHK, 25 bytes
Gui,Add,Checkbox
Gui,Show

Output -

Scratch, 2 blocks

Put this script in the default sprite (which comes with 2 costumes)

Online demo: https://phosphorus.github.io/app.html?id=143917094&full-screen=false

GeoGebra, 10 bytes
Checkbox[]

Entered into the input bar.
Here is a gif of the execution:

Whoah, GeoGebra. I remember that. It's been a while.

I know this is off-topic but do you go to Waterloo Collegiate Institute? Just out of curiosity, based on your name. I'm not a stalker don't worry :)

Python REPL, 45 bytes
from tkinter import*
Checkbutton(Tk()).pack()

I don't participate in CG nor do I often read these posts. However it really surprises me that you are allowed to use external modules. Isn't that cheating? I don't know how many bytes the Tk source code is, but really shouldn't these bytes be added to your byte count?

@Krazor tkinter is a standard library for Python (but even if it wasn't I'd only have to declare Python REPL + tkinter). This means that I can use it's features by simply importing it. The penalty you suggest is similar to asking users to include in the byte count the number of bytes in the source of the language you're writing in. Here we allow any language or module to compete as long as it was written and published publicly before the challenge was posted.

Okay, thank you for the clarification.

Tcl/Tk, 21 byte
Golfed
grid [checkbutton .c]

HTML with JavaScript - 136 124 120 115 113 111 109 79 bytes

-2 with thanks to @KritixiLithos
Reduced to 79 after some fantastic golfing from @Jan. Although the new version fits the requirements I have kept the old version for professional pride reasons.
While it is perfectly valid to use built-ins, I thought it was more fun to create my own from scratch. Tested with Chrome and Firefox. border:solid is there for IE compatibility but I don't know if it is actually needed in newer IE versions - I don't have IE available to test.
The px in the height is there for the benefit of "Run code snippet" so is not included in the "real" byte count. It works fine in the browser without it.

Previous version:

Can you do id=d to remove d=this?

@KritixiLithos - Indeed I can. Thanks and well spotted :)

You don't need to set the width, the rules say it can be any dimensions.
If you store the state on a property on this you'll save setting the id.
If you store this in a property you'll save a few bytes.
The align is unnecessary.
Since there are no spaces in the attribute strings, you don't need the quotes.

 79 bytes

@Jan - Thanks! The width bit is my own professional pride. If I don't set it it looks ugly and since this answer is never going to win and was just posted as an alternative I'll probably leave it there. Other than that some great hints. Many thanks. Will update tomorrow.

Thanks @Easterly. Updated the code but forgot the other bits. It's getting late.

The task is to make the code as short as possible. If that means abusing the language or the requirements, that's what you should do. I can relate to the feeling though

@Jan - Understood. I should stop thinking so much like a programmer and more like a golfer ;-) Thanks again.

Actually, for the challenge you could just skip the styling entirely in favour of just using a body element, making the entire application clickable. It won't work inside a code snippet, but you could post a jsbin instead like https://jsbin.com/pivumowuyi/edit?html,output

Now that's getting really smart :-) Feel free to post as your own answer. You will get +1 from me. I'm going to leave this as it is now.

No, it's really just an extension of your answer. The logic is still the same, it's just been shifted.

Still ok by me if you mention my answer ;-) "Improvement of the answer from ElPedro with permission" would work for me.

Why use 'x' which is 3 bytes. Why not use 8 which is one byte. Rules don't say the check has to be anything specific. @Jan

@Jan Also instead of saying t.e=!t.e you can just say t.e^=1 and knock off 2 more bytes

@Jan Also you don't need the closing tag > you can simply leave it off for another saved byte :D (As referenced in your main answer +1'd btw)

@AlbertRenshaw at OP's suggestion I posted my own version of this at http://codegolf.stackexchange.com/questions/109155/create-a-checkbox/109289#109289

@AlbertRenshaw - Thanks for the hints. I think Jan's solution is way ahead of any improvements I can make on this now :)

You can use a <fieldset> and remove all styling

You can remove ;border:solid and still meet the challenge requirements:
 (66 bytes). The works in IE 10 & 11, just like the original code does.

Minecraft 1.0.0, 1 byte
A lever in Minecraft meets all the criteria for a check box. This answer is only valid for older versions of the game where punching a lever still toggles it.

Scored using @Connor O'Brien's suggested byte count.

A difference of 3 between two answers hardly makes or breaks a consensus, but considering that Conor's answer is quite controversial (currently at +24/-10) and that the accepted answer is overwhelmingly well received (+17/-0), I think the latter should be used to score Minecraft answers.

However there are no structure blocks in Minecraft 1.0.0

It's one n in Conor, btw :)

Or you could rebind the left and right mouse buttons in any newer version to make it valid ;D

@ConorO'Brien Isn't that 1 block? Why 1 byte? I don't think mc stores every block as one byte...

Any version of Windows command line, 3 bytes
(cmd.exe, batch, powershell, start->run, whatever)
osk

Opens the on-screen-keyboard which has several "checkboxes" such as shift, ctrl, alt, capslock keys
Similar to the xgc answer, and inspired by the SmileBASIC answer screenshot.

TI-Basic, 15 bytes
While 1:Shade(0,9:Input :ClrDraw:Input :End

Fairly straightforward. The checkbox covers approximately 40% of the screen and alternates between black and white. When checked, the screen will look something like this:

Octave, 36 20 bytes
uicontrol('sty','c')

Thanks to @LuisMendo  saved 16 bytes!

uicontrol('sty','c') also works

@LuisMendo Thanks! 1/2 byte counts saved!

Excel VBA, 38 32 31 29 Bytes
Immediates Window function that inserts a checkbox of height=9 and width=9, at the cell A1 on the first sheet of the active Excel VBA project
Sheet1.CheckBoxes.Add 0,0,9,9

-6 Thanks to pajonk for replacing [A1],[A1],9,9 with 0,0,9,9
-1 for replacing Sheets(1) with [Sheet1]
-2 for realizing the above was stupid and using Sheet1 instead

Seems that 1,1,9,9 as arguments works as well.

You dont need the Sheet(1)., you can run this quickly enough in Excel but CheckBoxes is inherint to the active sheet

@Mr.Burns I have checked into this, but without directly referencing any Worksheet object, the CheckBoxes.Add method throws an error stating "Object Required"

@TaylorScott You are correct, I put the code in a sheet module rather than a normal module .. My mistake xD

SmileBASIC, 49 bytes
@L
O=T
TOUCH OUT T,,
X=T<O!=X
KEY 1,""[X]GOTO@L

 and  are an empty box and a checked box in SB's font.
Toggle the checkbox by touching the screen (the closest thing to clicking with a mouse)

Cheating answers:
0 bytes:
(the on-screen keyboard has buttons that act like checkboxes, such as the caps lock and insert keys)
14 bytes:
EXEC"SYS/SBGED

Opens up the built in graphics editor, which has multiple checkbox-like buttons

This is just brilliant, though I don't really understand what the 4th line is doing. Could you explain?

T<O is true when you stop touching the screen, and != is used as a logical XOR. X=X XOR (O && !T)

KV Lang, 8 bytes
CheckBox

assuming a really basic Python environment for kv lang to even run:
from kivy.app import runTouchApp
from kivy.lang import Builder
runTouchApp(Builder.load_string('CheckBox'))

This works basically because CheckBox is a Kivy widget included in a kivy.Factory as each widget from the standard library.
That simple string creates an instance of CheckBox and because of runTouchApp expecting a widget to run I can use Builder.load_string.
The background of load_string handles basically every kv string and if there is a single instance of a widget defined (e.g. CheckBox), then it is elevated to a root widget position, for example:
Application
    openGL Window
        root widget(mostly layout)
            main tree
            and some widgets
            ...

C#, 124 120 bytes
saved 4 bytes thanks to grabthefish.

note: because of edits, the picture doesn't exactly represent what the code makes, the "checkBox1" isn't displayed with the current code.
using System.Windows.Forms;class P{static void Main(){var a=new Form();a.Controls.Add(new CheckBox());a.ShowDialog();}}

ungolfed:

using System.Windows.Forms;
class P{
  static void Main(){
    var a=new Form();
    a.Controls.Add(new CheckBox());
    Application.Run(a);
    a.ShowDialog();
  }
}

If you didn't find anything about this on meta, ask about this on meta.

You can get rid of the spaces in var a = new Form();.

@Qwerp-Derp I removed them for counting, I just pasted the wrong thing, thanks.

you could use a.ShowDialog(); to save a few bytes

thanks @grabthefish, though c# still loses to java :(

a.Controls.Add(new CheckBox()) => new CheckBox(){Parent=a}

Let's discuss byte count: http://meta.codegolf.stackexchange.com/q/11650/32091.

Ruby with Shoes, 16 characters
Shoes.app{check}

Sample output:

Powershell v5+, 94 Bytes
($a=[Windows.Forms.Form]::new()).Controls.Add([Windows.Forms.Checkbox]::new());$a.ShowDialog()

This is pretty terrible, but I can't get the statements any shorter with either Add-Type or using namespace - and the variable is required, since I need to reuse the object to show the form, and Controls.Add() returns nothing usable.
ShowDialog is required on my system to have the box be interactive after running this command, otherwise the form is frozen.
also System.Windows.Forms.Form can only be shortened to Windows.Forms.Form before (at least my own) system stops auto completing it in a fresh session.

Nice! Might want to add that this requires version 5+.

@briantist updated, thanks.

HTML with JavaScript, 46 33 28 bytes
0

v2
0

v1

This is a variant on @ElPedro's answer: Create a Checkbox . Got down to 28 bytes with the help of @Albert Renshaw It could be further reduced, but that would make it identical to Create a Checkbox
The whole application area is clickable. It will display 0 in the off state and 1 in the on state. Try it out at https://jsbin.com/nuhetiyocu/1/edit

Here's a neat variation at 39 bytes. <body onclick=t=this;t.innerHTML^=t?1:0 The 16 pixel rule between state change is up for debate though.

38 <body onclick=this.innerHTML^=this?1:0

36 <body onclick=this.innerHTML^=1+this

Nice on 33! That's a great solution hhahah

Oh no with your help I'm down on 33 already :)

I dont think I can beat that lol

28 0

Now that there's always a value inside the container, it could be changed from the body to a different element. But I just noticed that would make it identical to another answer http://codegolf.stackexchange.com/questions/109155/create-a-checkbox/109295#109295 so I'm just leaving it as is

I always feel so original here until I see another answer in the same thread identical to my code  hahaha

Got a javascript solution down to 24 bytes now, different approach completely than what we were doing. http://codegolf.stackexchange.com/a/111422/16513

Operation Flashpoint scripting language, 273 bytes
To show the checkbox:
createDialog"b"

But first it must be defined:
Save the following to a file named description.ext in the mission folder:
class b{idd=999;movingEnable=1;class controls{class c{idc=457;x=0.1;y=0.1;w=0.1;h=0.1;text="";action="if(ctrlText 457=={})then{ctrlSetText[457,{V}]}else{ctrlSetText[457,{}]}";type=1;style=2;colorText[]={1,1,1,1};font="tahomaB36";sizeEx=0.1;}}}

The checkbox in action:

Pug, 20 bytes
input(type=checkbox)

Besides which I count is as 23. If you remove the quotes it still works on Firefox and Chrome (can't test on IE) and would come in at 21 in which case I would consider it an improvement on the example and therefore valid.

@heonlygusti - indeed but without the quotes I would have upvoted :-) btw, the downvote wasn't me.

I would have up-voted if it wasn't for those quotes, which are not needed.

@theonlygusti not at all. Give it a try.

VBA (Word), 74 57 bytes
-17 thanks to Taylor Scott
Sub a()
f = a.FormFields.Add(Selection.Range, 71)
End Sub

Filename of the document should be a.

You can replace the wdFieldFormCheckBox with 71 (the integer value of the wdFieldFormCheckBox constant) for a savings of 17 bytes

I think you can remove the newlines for -2 bytes.

Clojure, 201 195 145 127 bytes
(ns c(:require[quil.core :as q]))(def a(atom nil))(q/defsketch b :draw #(q/background(if@a 0 99)):mouse-clicked #(swap! a not))

-6 bytes by getting rid of the need for m/fun-mode.
-50 bytes by removing the :setup and :size options, since they are defaultable and unnecessary in non-fun-mode. Also removed the unnecessary import for middleware.
-18 bytes thanks to @ASCII-only. Changed to "smaller" colors, and removed an unnecessary space before the dereference operator (@).
Creates a Quil sketch (a Clojure library that provides a layer over Processing), therefore, this requires the Quil library to run.
(ns bits.golf.checkbox
  (:require [quil.core :as q]))

; Mutable global variable to hold the toggle state
(def a (atom nil))

(q/defsketch b
         ; Draw the background color to be either black or red depending on the toggle state.
         :draw #(apply q/background (if @a [0 0 0] [255 0 0]))

         ; Negate the state on mouse click
         :mouse-clicked #(swap! a not))

Can't you replace 255 with 99? Also I'd try removing spaces before/after symbols and seeing if it still works

@ASCII-only yes, I could. It made a rant ugly color though iirc, and for some reason I prioritized that at the time. And no, this is as much space as I can remove unfortunately.

@ASCII-only The problem is symbols can contain almost any character, so really the only "safe neighbours" that you can remove spaces around are any kind of bracket, or quotes. Luckily this is a lisp to the former is pretty prevalent.

Hmm maybe [0 0 99] then? (some kind of dark blue)

@ASCII-only Actually, I think I can drop the 0s now that I think about it. I think Quil auto pads the front with 0s if the vector is to short. If I remember latest I'll fix it up. Thanks for getting me thinking.

Yeah, (ns c(:require[quil.core :as q]))(def a(atom nil))(q/defsketch b :draw #(q/background(if@a 0 99)):mouse-clicked #(swap! a not)) works,  I just read the docs, looks like it doesn't autopad, but it uses the value as a grayscale value. (Plus @a doesn't need a space before it)

@ASCII-only Thanks for the suggestions! I was occupied by the color channel challenge (and work) all day today. I'll try to incorporate your changes tomorrow.

Jolf, 19 bytes
"<Ξ♠ΐ♠type=Ξ\t5δbox>

Replace \t with a tab literal and ♠ with 0x06. Try it here!
"<Ξ♠ΐ♠type=Ξ\t5δbox>
"...................   string containing...
 <                     "<"
  Ξ♠ΐ♠                 compressed for "input "
      type=            "type="
           Ξ\t5δ       compressed for "CHECK"
                box    "box"
                   >

This displays a checkbox to the output element.

Slim, 21 Bytes
input type="checkbox"

Try it here
So yeah. One of slim's major features is that < and > characters are not there. So basically, I get 2 bytes less than the creator of the question!

HTML still beats it though :) http://codegolf.stackexchange.com/a/109189/44888

remove quotes for better points

@wat It seems that's not allowed in Slim

@Metoniem That's excessively ironical.

Bash + zenity, 31
zenity --checklist --column a a

Bash (+yad), 23 bytes
Golfed
yad --form --field :chk

YAD is a program that will display GTK+ dialogs, and return (either in the return code or on standard output) the users input. This
         allows you to present information, and ask for information from the user, from all manner of shell scripts.

Yad is available in Debian and Ubuntu repositories (and probably others).
Demo

AutoIt, 78 Bytes
GUICreate(0)
GUISetState(GUICtrlCreateCheckbox(0,0,0))
Do
Until GUIGetMsg()=-3

Opens a maximized window that can be closed like any other windows window. The maximization and ... on-top-ness is a side effect of the golfing.

How would I run this on Linux?

@wat wine AutoIt3.exe script.au3, where the script.au3 file contains this code.

Python, 62 bytes
from tkinter import*
a=Tk()
Checkbutton(a).pack()
a.mainloop()

C#, 814 bytes
Out of interest I decided to see how many bytes it would take to use a console application in C# using the mouse to change the checked state. There is no built in support so you have to use unmanaged code and it get's very long, very fast. There might be room for improvement but it's never going to be short.
Note: It does seem to change the checked state when the mouse is pressed and is moved at the same time. But seeing as this is never going to compete I decided to leave that be as a quirk.
using System;using System.Runtime.InteropServices;class P{static void Main(){int m=0,n=0,c=0;var h=GetStdHandle(-10);GetConsoleMode(h,ref m);SetConsoleMode(h,m&=~64);new System.Threading.Thread(()=>{for(;;){var r=new[]{new r()};ReadConsoleInput(h,r,1,ref n);Console.Clear();if(r[0].e==2&&r[0].m.s==1)Console.BackgroundColor=++c%2<1?0:(ConsoleColor)1;}}).Start();}[StructLayout((LayoutKind)2)] struct r{[FieldOffset(0)]public int e;[FieldOffset(4)]public m m;}struct m{int p;public int s;}[DllImport("kernel32.dll")]static extern IntPtr GetStdHandle(int h);[DllImport("kernel32.dll")]static extern bool GetConsoleMode(IntPtr h,ref int m);[DllImport("kernel32.dll")]static extern bool SetConsoleMode(IntPtr h,int m);[DllImport("kernel32.dll")]static extern bool ReadConsoleInput(IntPtr h,[Out]r[]r,int l,ref int n);}

And the formatted version:
using System;
using System.Runtime.InteropServices;

class P
{
    static void Main()
    {
        int m = 0, n = 0, c = 0;

        var h = GetStdHandle(-10);
        GetConsoleMode(h, ref m);
        SetConsoleMode(h, m &= ~64);

        new System.Threading.Thread(() =>
        {
            for (;;)
            {
                var r = new[] { new r() };
                ReadConsoleInput(h, r, 1, ref n);

                Console.Clear();
                if (r[0].e == 2 && r[0].m.s == 1)
                    Console.BackgroundColor = ++c % 2 < 1 ? 0 : (ConsoleColor)1;
            }
        }).Start();
    }

    [StructLayout((LayoutKind)2)]
    struct r
    {
        [FieldOffset(0)]
        public int e;
        [FieldOffset(4)]
        public m m;
    }

    struct m
    {
        int p;
        public int s;
    }

    [DllImport("kernel32.dll")]
    static extern IntPtr GetStdHandle(int h);

    [DllImport("kernel32.dll")]
    static extern bool GetConsoleMode(IntPtr h, ref int m);

    [DllImport("kernel32.dll")]
    static extern bool SetConsoleMode(IntPtr h, int m);

    [DllImport("kernel32.dll")]
    static extern bool ReadConsoleInput(IntPtr h, [Out]r[] r, int l, ref int n);
}

CSS, 46
Assumes a minimal HTML document, not unlike this CSS Hello World submission.
This one avoids the extra "X" of the old 42 char solution, making it conform with the rules.
NOTE: Seems to only work in Firefox (51.0.1)

* :after{content:'X'}*:active :after{all:unset

CSS, 42 (old solution)

:after{content:'X'}:active:after{all:unset

Not switching state by click, but switches to other state while muose button is pressed.

@Qwertiy, which browser are you using?

Chrome 56 on Windows 7 x64. Anyway, I expect it to be in any browser as :active should work only while mouse button is down. What browser do you use with the other result?

@Qwertiy, Firefox, as was clearly stated above.

Checked at my Firefox 52.0 beta 9 x32 - absolutely the same results as in Chrome. By the way, 42-byte solution has 3 states intead of 2: both Xs are visible, only the fisrst X is visible and both X are invisible. What OS are you using?

@Qwertiy That's why it's labeled the "old solution" :) I'm using macOS 10.12.3, and with Firefox 51.0.1 both solutions switch their state with a click – unlike how Chrome behaves.

Java 1.4+, 104 bytes
import java.awt.*;interface g{static void main(String[]a){new Frame(){{add(new Checkbox());show();}};}}

-13 thanks to Kevin Cruijssen.

Groovy, 67 bytes
import java.awt.*;{new Frame(){{add(new Checkbox())setVisible(1)}}}

Does !0 work instead of 1>0? It does in groovy.

The exact same thing is 68 bytes in groovy excluding main method signature and ending ;.

@GurupadMamadapur in groovy it'd just be setVisible(1). In Java 8 it works; in all versions of java though, that is not valid syntax.

Oh okay. I just tried executing the groovy code (V. 2.4.7), I got EOF error. This works though - import java.awt.*;new Frame(){{add(new Checkbox());setVisible(!0)}} (67 bytes)

Ah, you're right. It was treating the .*{ as a vectorized closure on java.awt so the ; is required.

That closure won't execute - Error-Ambiguous expression could be either a parameterless closure expression or an isolated open code block. Also, 1 won't evaluate to true. It raises MethodMissing exception.

@GurupadMamadapur it is a parameter-less closure, it does run but I don't have to add x= and x() as per a sandbox discussion. But you're right about !0 vs 1. If you want it to run, surround the closure with (<closure>)().

For your Java answer, you are using main but it's not in a class so I'm not sure how it would work... Also you can use String[]a instead of String[] args

Uh, you need to wrap the java code in a class, like interface g{ ... } (interface because that will let you drop public from public static void main

java: javac says: reached end of file while parsing. there is a closing bracket missing

Spaces ... >_< ... String[] args=>String[]args. And is it possible to change the name of the argument array?

This can be import java.awt.*;interface g{static void main(String[]a){new Frame(){{add(new Checkbox());show();}};}} instead (103 bytes). And I don't know Groovy, but maybe it also has a show() method?

@KevinCruijssen only valid in 1.8, invalid modifiers for versions below 1.8.

@MagicOctopusUrn Oh, didn't knew show() was that new. Well, you can still golf String[] args to String[]a.

@KevinCruijssen made a mistake, had the wrong JRE loaded, you're right show is fine.

P5.js 35 26 bytes

function setup(){createCheckbox()}
not really fun, but it works.
setup=s=>createCheckbox()

-9 bytes thanks to Kritixi

setup=s=>createCheckbox() is shorter

FLTK, 48 characters
Function{}{}{Fl_Window{}{}{Fl_Check_Button{}{}}}

Sample run:
bash-4.3$ fluid -c checkbox.fl

bash-4.3$ fltk-config --compile checkbox.cxx
g++ -I/usr/include/cairo -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/include/pixman-1 -I/usr/include/freetype2 -I/usr/include/libpng16 -I/usr/include/freetype2 -I/usr/include/cairo -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/include/pixman-1 -I/usr/include/freetype2 -I/usr/include/libpng16 -g -O2 -fvisibility-inlines-hidden -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE -D_THREAD_SAFE -D_REENTRANT -o 'checkbox' 'checkbox.cxx' -Wl,-Bsymbolic-functions -lfltk -lX11

bash-4.3$ ./checkbox

Sample output:

C#, 151 139 bytes
This is a longer approach than @satibel his answer, but it's completely different and doesn't require a form. Since I couldn't comment about if I could use key presses instead of mouse clicks (not enough rep.) I'm not 100% sure this is allowed, so let me know!
EDIT: Managed to lose 12 bytes thanks to some of my own improvements, and some are thanks to @TheLethalCoder
Golfed
using c=System.Console;class p{static void Main(){for(int _=1;;_++){c.ReadKey();_%=2;c.BackgroundColor=(System.ConsoleColor)_;c.Clear();}}}

Ungolfed
using System;
class p
{
    static void Main()
    {
        int _ = 0;
        for (int _=1;;_++)
        {
            Console.ReadKey(); //Wait for user input
            _%=2; //Prevent integer from overflowing at some point
            Console.BackgroundColor = (System.ConsoleColor)_; //Set Console background color to either 0 (black) or 1 (darkblue) depending on if our integer is even
            Console.Clear(); //Clear console window to get rid of input. This also causes the whole console window to change color
        }
    }
}

I know it's kind of tricky since it works with keypresses rather than mouseclicks, so let me know if that's allowed. If it's not, I'll happily remove my answer, or write a new one instead!

You can do it using mouse clicks but the code get's really long

Very very long in fact: http://codegolf.stackexchange.com/a/109383/38550

@TheLethalCoder That's an amazing answer. I knew it was possible, but I didn't even dare to try.. GG to you sir! (Can't comment on other answers than my own yet, sorry)

Amazing that you can do it (I did a lot of googling and then hacking on the result to get it to work and be "short"). Just not amazing with how long it is! And no worries keep posting good answers and you will get there.

Improvement points (untested on length but should save you bytes): using c = System.Console; instead of using System; and then do c.ReadKey(); etc, the _++; and _%=2; can be combined using post increment to ++_%=2; (I think that should work although I haven't tested), < 1 instead of == 0, Might be able to assign _ on the BackgroundColor line but you'd have to experiment with it.

@TheLethalCoder Oh hey, that's interesting. Let me try a few of those! I thought of using c=System.Console; but figured it was longer than writing Console 3 times.. Only I forgot I could then remove using System;

Vim: 13 Bytes Keystrokes
iq<Esc>:nm a g??<CR>

Press a and toggle between q and d (feels like a lever to me ...)
Explanation:
 iq<Esc>   " insert a q char
 nm a      " create a normal mapping toggled by a
 g??       " rot13 the current line, q -> d -> q ...
 <CR>      " validate the mapping

The checkbox has to be activated by the mouse, not the keyboard. I think you can do :nm <LeftMouse> g?? instead

Javascript, 24 23 21
for(i=0;;)alert(i=!i)

i=0;while(1)alert(i=!i)

i=0;while(1)alert(++i%2)

WARNING: Might cause you to have to force-quit your browser
This one is a neat solution because it actually is not a check box and has none of the logic of a check box, but on the surface behaves very similar to a check box (toggling change of state on button press) due to exploiting the action-based delay in javascript alerts, and meets all of the criteria of rules defined in the challenge.
Try it here (*Might cause you to have to force-quit your browser)

Wow, this is clever. Usage of text as an image, I like it.

C (Win32 Console application), 143 131 bytes
#include<windows.h>
main(){MSG m;for(CreateWindow("button","",1<<28|3,0,0,8,80,0,0,0,0);GetMessage(&m,0,0,0);DispatchMessage(&m));}

Red, 11 bytes
view[check]

The above code was rejected by SE as too short for a post, hence this addendum

Java, 69 bytes
a->{a.removeAll();a.add(new java.awt.Checkbox());a.setVisible(1>0);};

Just a not-so-self-explanatory Consumer<Frame>. It takes a Frame, removes everything in it, puts a checkbox, and then makes sure the Frame is displayed.

OP specified a program, not a function.

Java 8 is also important specification here.

@Pavel Restricting to just programs requires explicitly specifying "full program" rather than just "program"

What's your justification for being able to take a Frame as input?

Coding, 21 bytes
>input(checkbox)@type

Finally a perfect time to use this language!

Racket, 98 bytes
#lang racket/gui
((λ(f)(new check-box%[parent f][label""])(send f show #t))(new frame%[label""]))

At least I have a few bytes on the Clojure answer!

VBA, 42 bytes
ActiveSheet.CheckBoxes.Add(1,1,8,8).Select

Best I could get with this!

 Emacs Lisp, 58
(and(widget-create'checkbox)(use-local-map widget-keymap))

VB.NET, 67 (program) + 37 (additional switches) = 104
VB.NET Windows Forms Application, 67 chars
Class F
Inherits Form
Dim C=New CheckBox With{.Parent=Me}
End Class

Compile it with
vbc.exe *.vb /main:F /imports:System.Windows.Forms

Not using /target:winexe switch. Assume that additional console is ok.

PS: Question about byte count.

Nice. I don't think you need the Inherits Form if you specify you're using Windows Form Application.

@obarakon, but I don't specify that. That's just a file, not the part of solution. In case of winforms solution I wouldn't write main and imports switches by myself.

I get the desired form+checkbox just running Class F Dim C=New CheckBox With{.Parent=Me} End Class in an empty WFA project.

@obarakon, let's discuss byte count: http://meta.codegolf.stackexchange.com/q/11650/32091. By the way, in case of winforms app you have partial class because of designer.

JQuery, 50 Bytes
$("<input type=checkbox>").appendTo(document.body)

Welcome to PPCG!

SAS, 145
proc pmenu catalog=work.c;menu m;item i dialog=d;dialog d '&1';text #1 @1 'A';checkbox #2 @1 'B';run;quit;%window w menu=work.c.m '';%display w;

This creates and displays a menu with an item that opens a dialogue box with a checkbox. It might be possible to golf it further, but I'm reluctant to try as this has already led to several crashed sessions :(

C# (Windows Form Application), 82 bytes
using System.Windows.Forms;class F:Form{public F(){Controls.Add(new CheckBox());}}

Saved bytes thanks to @Qwertiy

Full program, not a function.

Why do you need namespace? And partial class?

Let's discuss byte count: http://meta.codegolf.stackexchange.com/q/11650/32091.

C++ with SFML, 401 bytes
-4 bytes thanks to Zacharý
#include<SFML\Graphics.hpp>
#include<cassert>
using namespace sf;int main(){RenderWindow w(VideoMode(300,300),"");Texture a,b;assert(a.loadFromFile("a.png")&&b.loadFromFile("b.png"));Sprite p(a),q(b);bool c=0;while(w.isOpen()){Event e;while(w.pollEvent(e)){if(e.type==Event::Closed)w.close();if(e.type==Event::MouseButtonPressed)c=!c;}w.clear(Color::White);if(c)w.draw(q);else w.draw(p);w.display();}}

Screenshot of the boxes :
Checked :

And unchecked :

This uses the SFML library
The checkbox changes state on a sf::Event::MouseButtonPressed event ( left click, right click, middle click... )
If you want to test, after the creation of the render window, you may want to set the framerate limit to 60 fps ( using the line w.setFramerateLimit(60) ), so your computer won't burn.
This requires 2 checkboxes images in the directory where the app runs ( a.png and b.png ). For the reason it uses images, i don't know if my answer is invalid ( standard loophole ? ), but since it's needed to do graphic output...

a.loadFromFile("a.png") && b.loadFromFile("b.png") => a.loadFromFile("a.png")&&b.loadFromFile("b.png"). if (e.type=>if(e.type. Does your code editor auto-format or something?

Forgot one... VideoMode(300, 300) => VideoMode(300,300)

@Zacharý Yes, it format every new semi colon.

Javascript, 14 bytes
alert(alert())
In most browsers, opening two alerts causes a checkbox to be added to the second that asks whether the user wants to keep allowing alerts.

I don't see anything in the rules that means it's not ok to first have a button that the user has to push before seeing the checkbox.

Actually the question's owner explained in a comment: “the checkbox should show up right away”. Hence the earlier alert(alert()) and alert(alert(1)); answers were deleted. ☹

Bah, comments. Rules should go in the rules.

SVG, 79 characters
<svg><input type="checkbox"/>

Yes, there is a closing tag missing, but FireFox and Chrome display it ok.

Funky 2, 83 Bytes
withdraw withnewWindow(){whenonDraw{setColor(a,1)box(0,0,8,8)}whenonMouseDown a=!a}

Cleaned up and commented
with draw{                  $# With the draw library
    with newWindow(){       $# Open a new window with the default parameters
        when onDraw{        $# Each draw frame of the window. This can't be placed in onMouseDown due to Funky2 Automatically clearing the window
            setColor(a,1)   $# Set the color to either Green or Yellow depending on if a is 1 or not (Set color automatically adds arguments)
            box(0,0,8,8)    $# Draw a box of size 8 by 8.
        }
        when onMouseDown{   $# When any mouse button is clicked
            a=!a            $# Set a to not a. Conveniently, setColor casts it's argument to a number, so this flips between 0 and 1.
        }
    }
}

Output

Desmos, 34 bytes
Expressions(27 bytes):
min(x,y)<9
C=hsv(0,0,a)
a=1

(Make sure to select the color corresponding to C for min(x,y)<9, set the fill opacity for min(x,y)<9 to 1, and make sure that the graph is on the default viewport.)
On-click statement(6 bytes):
a->1-a

(27+6 is 33 bytes, but I have to add one byte because of this.)
Clicking anywhere on the graph will switch the color of the graph from white to black and vice versa.
Try It On Desmos!
Try It On Desmos! - Prettified

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