text:
N-dimensional Circles!
Write a program that takes two numbers as its input. The first one is the number of dimensions - 0 for a dot, 1 for a straight line, 2 for a circle, 3 for a sphere. The second number is the radius of the object, or, if it's 1-dimensional, the number itself. Output 0 for 0 dimensions. The output is the length/area/volume of the object.
If we call the first number n, the second one r, and the output x, we get that:

for n = 0, x = 1
for n = 1, x = 2×r
for n = 2, x = r2×π
for n = 3, x = (4/3)×r3×π
and so on... if you want, though.

Notes:

Cases when one or both numbers are negative, or when the first number is not whole, don't need to be covered.
The program must not read from any file and the only input are those two numbers.
The output should use only numerals (e.g. not "14*pi"), and should be accurate to at least two decimal digits.
As for n = 0, you can output 0 if it makes the code shorter.
Extra swag for an answer covering even 4 and more-dimensional "spheres"!
It's code-golf, so the shortest answer in bytes wins!

Examples:
 1 1 -> 2

 2 3 -> 28,27

 3 1 -> 4,19

 3 4,5 -> 381,70

 1 9.379 -> 18.758

 0 48 -> 1

Yay! I love false MathJax equations in posts!

Should we output 0 or 1 for n = 0?

@LegionMammal978 You should output 1, but if it would be really extending your code, you can add a solution with 0 to your answer.

@LegionMammal978 Sorry, no, you can't. BTW it's mentioned in the question.

Not to critic, but I don't see how a line can be considered as a 1d circle...

@xem Consider a circle as all points that are within a given distance from the center

Math types would call these "balls" of various dimensions.  The set of points with distance from the origin == r is the sphere, the set of points with distance from the origin <= r is the ball.  Then these are 0-ball = point, 1-ball = segment, 2-ball = disk, 3-ball = ball, 4-ball, 5-ball, et c. (listed as "n-ball = common name").

"Output 0 for 0 dimensions" and "for n = 0, x = 1" contradict each other. Could you please choose one (or clarify that both are allowed)?

Jelly, 13 bytes + extra swag
÷2µØP*÷!
ç×*@

Try it online!
Works for any dimension, so long as the fixed value of π yielded by ØP (3.141592653589793) is accurate enough.
How?
÷2µØP*÷! - Link 1: n, r
÷2       - n / 2
  µ      - monadic chain separation
   ØP    - π (3.141592653589793)
     *   - exponentiate: π^(n/2)
       ! - Pi(n/2): Gamma(n/2 + 1)
      ÷  - divide: π^(n/2) / Gamma(n/2 + 1)

ç×*@     - Main link: n, r
ç        - call last link (1) as a dyad: π^(n/2) / Gamma(n/2 + 1)
  *@     - exponentiate with reversed @rguments: r^n
 ×       - multiply: r^n * π^(n/2) / Gamma(n/2 + 1)

Well done for beating Mathematica!

Congrats, you won!

Mathematica, 18 bytes, up to ~168.15 trillion dimensions
Pi^(a=.5#)/a!#2^#&

Anonymous function. Takes two numbers as input, and returns an inexact number as output. Works with any number of dimensions. Outputs 1. for n = 0. Uses the formula from Volume of an n-ball on Wikipedia.
Explanation
We are attempting to compute πn/2/Γ(n/2 + 1)·Rn, or N[Pi^(n/2)/Gamma[n/2 + 1] R^n] in Mathematica. In our case, # (first argument) is n and #2 (second argument) is R. This leaves us with N[Pi^(#/2)/Gamma[#/2 + 1] #2^#] &, which can be golfed as follows:
N[Pi^(#/2)/Gamma[#/2 + 1] #2^#] &
Pi^(.5#)/Gamma[.5# + 1] #2^# &    (* replace exact with approximate numbers*)
Pi^(.5#)/(.5#)! #2^# &            (* n! == Gamma[n + 1] *)
Pi^(a=.5#)/a! #2^# &              (* replace repeated .5# *)
Pi^(a=.5#)/a!#2^#&                (* remove whitespace *)

and thus, our original program.

Nice answer - that was fast! Just for clarification: To how many digits is the output correct? How many dimensions it's possible to calculate?

@RudolfL.Jelínek It outputs to about 5 significant figures, and it works for all n up to 168,146,894,169,516 for r = 1 (albeit with less figures).

@LegionMammal978 which formula? I'm quite certain you don't use the gamma function there

@Angs n! = Γ ( n + 1).

Could you please ungolf and explain each part of the code? Some less experienced users maybe don't see what's in the code. Thanks!

Oh, ! works for non-integrals too. Using Mathematica for this almost feels like cheating… :)

R, 75 40 38 bytes (plus extra swag)
Well, looks like I could golf this down by giving in and using the gamma function rather than recursive functions.
function(n,r)pi^(n/2)/gamma(n/2+1)*r^n

Defines an anonymous function to calculate the volume of an n-dimensional hypersphere of radius r.
Some examples:

1 1 -> 2
0 48 ->  1
2 3 -> 28.27433
3 4.5 -> 381.7035
7 7 -> 3891048
100 3 -> 122051813

Swagless solution, 38 34 bytes
For a few bytes less, you can have an anonymous function that only works for dimensions 1 to 3. Returns numeric(0) for n=0, and NA for n>3. (numeric(0) is a numeric vector of length 0; NA is for "not available".) Performance is otherwise identical to the general solution above.
function(n,r)c(1,pi,4/3*pi)[n]*r^n

₊₁ for the SSSSSWWWWWAAAAAAAGGGGGGGGGG!

JavaScript (ES6), 45 bytes + extra swag
Recursive formula from wikipedia, should work for any number of dimension
f=(n,r)=>n<2?n?2*r:1:f(n-2,r)*2*Math.PI*r*r/n

JavaScript, 61 51 49 43 bytes
0-3 dimensions are supported because there is no 4th dimension.
Thanks to @Hedi for saving 7 bytes
d=(n,r)=>r**n*(n<2?n+1:Math.PI*(n<3?1:4/3))

Creates function d. Then raises r to the nth power and then multiplies it with a number depending on n using ternary operators. Outputs 1 for n=0
Gives output to at least 2 decimal places (10+ dp)
Here's a snack snippet!

var N = document.getElementById("n");
var R = document.getElementById("r");
N.value="3";//default
R.value="4.5";//default
d=(n,r)=>r**n*(n<2?n+1:Math.PI*(n<3?1:4/3));
var b = document.getElementById("b");
b.onclick = function() {
  var s = document.getElementById("s");
  var n = document.getElementById("n").value;
  var r = document.getElementById("r").value;
  s.textContent = d(parseFloat(n),parseFloat(r));
}
span {border:1px solid black;padding:10px;font-size:30px;}
Value of n: <input id="n" type="number"></input>
Value of r: <input id="r" type="number"></input>

<button id="b">Calculate!</button>

THERE IS NO 4TH DIMENSION

Beat my non-posted solution by... by a lot. +1!

what a dumb video…

@SargeBorsch At least it proves my point :)

You can save bytes using Math.PI only once and you can make n<1 and n<2 the same case (will return 1 for n=0) d=(n,r)=>r**n*(n<2?n+1:Math.PI*(n<3?1:4/3))

@Hedi Thanks! You saved me 7 bytes!

@SargeBorsch Haha yup dumb video - 0:40 3 dimensions that behave in the same way and one that behaves in a different way - At that point he seems to be saying there is a 4th dimension, but no 1st, 2nd or 3rd!

@LevelRiverSt Well that was the first result I was on the web ¯\(ツ)/¯

Haskell, 74 65 36 bytes + extra swag
0%r=1
1%r=2*r
n%r=2*pi*r^2/n*(n-2)%r

Recursive formula, works for all dimensions that can be presented exactly as a double-precision floating point number but will loop infinitely for non-integral dimensions. The old version for posteriority's sake:
n%r=(max 1$1-(-1)**n)*(2*pi)^(floor$n/2)*r**n/product[n,n-2..1.1]

Works for all dimensions. Uses the formula from the tau manifesto.
product[n,n-2..1.1] is a double factorial hack that won't count zero for n==2

MATL, 17 bytes
3:^[2P4*P/3]*1hi)

This works up to 3 dimensions only. Inputs are in reverse order, that is: r, then n.
Try it online!
Consider r=3, n=2 as an example.
3:         % Push array [1 2 3]
           % STACK: [1 2 3]
^          % Take r implicitly, and raise it to [1 2 3] element-wise
           % STACK: [3 9 27]
[2P4*P/3]  % Push array [2 pi 4*pi/3]
           % STACK: [3 9 27], [2 pi 4*pi/3]
*          % Multiply element-wise
           % STACK: [6 28.2743 113.0973]
1h         % Append 1
           % STACK: [6 28.2743 113.0973, 1]
i)         % Input n and use it as modular index into the array. Display implicitly
           % STACK: 28.2743

Racket 69 bytes (plus extra swag)
Uses recursive formula from https://en.wikipedia.org/w/index.php?title=Volume_of_an_n-ball&section=3#Recursions
Including suggestions by @wchargin
(define(v d r)(match d[0 1][1(* 2 r)][_(/(* 2 pi r r(v(- d 2)r))d)]))

Ungolfed (v=volume, d=dimensions, r=radius):
(define(v d r)
  (match d
    [0 1]
    [1 (* 2 r)]
    [_ (/ (*  2   pi   r   r   (v (- d 2) r)  )
          d)]
    ))

Testing:
(v 1 1)
(v 2 3)
(v 3 1)
(v 3 4.5)
(v 1 9.379)
(v 0 48)

Output:
2
28.274333882308138
4.1887902047863905
381.7035074111599
18.758
1

I highly doubt that this is legitimate: you're using the recursive function without counting its definition in the byte count. That is, the expression that you're scoring as 67 bytes is not valid Racket, as v is unbound (not to mention the other parameters). Surely you need to count the (define(v d r)) as well? This brings you up to 82 bytes…

…but you can shave off four bytes from that by replacing your cond with nested if expressions, bringing you down to 78 bytes with (define(v d r)(if(= d 0)1(if(= d 1)(* 2 r)(*(/(* 2 pi(* r r))d)(v(- d 2)r))))).

…and shave off three more by using a match to get (define(v d r)(match d[0 1][1(* 2 r)][_(*(/(* 2 pi(* r r))d)(v(- d 2)r))])).

Thanks for great suggestions. I am including these in the answer.

@wchargin : I could reduce 9 more bytes by repositioning (v (- d 2) r) in formula and by using only "r r" instead of "(* r r)" since it is already in a multiplication formula.

Java/C/C++/C#, 69 67 bytes + extra swag!
Edit: Saved 2 bytes thanks to @AlexRacer
A dyadic function - first argument is number of dimensions, second is the radius of the n-ball.
float v(int n,float r){return n<1?1:n<2?2*r:6.283f*r*r*v(n-2,r)/n;}
Recursive formula for the volume of an n-ball:
Vn=(2πr2Vn-2)⁄n
Whoa! Java (my test language) beats Scala here, thanks to the terse ?: ternary syntax! This function is syntactically correct in all 4 languages in the heading, and I have tested it with C (MinGW GCC 5.4.0), & C# (VS Ultimate 2016, C# 6.0). I'm assuming that it will work in C++ too, so there. Since this function is pretty much library-independent, it should work in any C-like language with similar syntax.

Wow! I thought I'd never get a Java answer! Got it - thanks! And, as a bonus, it beat some answers and got the extra swag! ₊₁

n==0 can be shortened to n<1 and also n==1 to n<2

Haskell, 52 bytes for tab indent 42 bytes + extra swag
Edit: Saved 10 bytes thanks to @WChargin
A dyadic curried function - first argument is number of dimensions, second is the radius of the n-ball.
v 0 r=1
v 1 r=2*r
v n r=2*pi*r*r*v(n-2)r/n

Recursive formula for the volume of an n-ball:
Vn=(2πr2Vn-2)⁄n
Save this as a separate script file and run with GHCi, with a function for testing v for output, e.g., show (v 3 4.5). I did not test this, please let me know if this doesn't work.
Old program with 6.2832 approximation for 2π replaced (50 bytes with tab indent):
let v 0 r=1
    v 1 r=2*r
    v n r=2*pi*r*r*(v(n-2)r)/n

This can be used with GHCi in multiline mode (using :set +m or enclosing the code between :{ & :}, the enclosures being on their own lines. Tester function required.
Static typing with full-program type inference comes into play here, allowing Haskell to do far better than Scala, and approaching Groovy, but not quite beating it thanks to the pattern match instead of a ternary, involving some character repetition.

51 if using layout directly, 49 if you substitute 2*pi for 6.2832, and 47 if you drop the parentheses around the recursive call: let{v 0 r=1;v 1 r=2*r;v n r=2*pi*r*r*v(n-2)r/n}…

…but more typical scoring is to submit as a separate script file; drop the let{} and replace my semicolons with linefeeds to get just 42 bytes (without trailing newline).

@WChargin I've been learning Haskell for a whole 2 days, so thanks for the pointers. I erred on the side of caution with the parentheses as I'm not sure about operator vs function call precedence in Haskell

Python 3, 76 72 68 bytes + extra swag!
Recursive solution with extra swag!
Returns 0 for n=0
from math import*
f=lambda n,r:n*r*2*(n<2or pi*r/n/n*(f(n-2,r)or 1))

Old approach (1 for n=1):
from math import*
f=lambda n,r:1*(n<1)or r*2*(n<2)or 2*pi*r*r/n*f(n-2,r)

Recursive formula from Wikipedia.
Try it online.

Python 3, 56 bytes + extra swag!
Straightforward with extra swag!
from math import*
lambda n,r:pi**(n/2)*r**n/gamma(n/2+1)

Standard formula.
Try it online

Perl, 63 bytes + extra swag
@a=1..2;push@a,6.283/$_*@a[$_-2]for 2..($b=<>);say$a[$b]*<>**$b

Accepts two integers n and r, one at a time, then outputs the n-volume for given radius r of an n-sphere.  When n = 0, V = 1, and when n = 1, V = 2r.  All further dimensions are calculated by the following formula:

Since rn is the radius's factor in every formula, I leave it out of the base calculation and only apply it at the end.
2π is approximated in the code by 6.283.

Nice and recursive, and ₊₁ for showing the recursive formula.

Scala, 53 bytes
{import math._;(n,r)=>pow(r,n)*Seq(1,2,Pi,Pi*4/3)(n)}

Sorry, no extra swag for me :(
Explanation:
{                     //define a block, the type of this is the type of the last expression, which is a function
  import math._;        //import everything from math, for pow and pi
  (n,r)=>               //define a function
    pow(r,n)*             //r to the nth power multiplied by
    Seq(1,2,Pi,Pi*4/3)(n) //the nth element of a sequence of 1, 2, Pi and Pi*4/3
}

JavaScript (ES6), 39 bytes, no swag
(n,r)=>[1,r+r,a=Math.PI*r*r,a*r*4/3][n]

CJam (27 bytes with extra credit)
{1$_[2dP]*<f*\,:)-2%./1+:*}

Online test suite. This is an anonymous block (function) which takes arguments d r on the stack and leaves the result on the stack.
Dissection
The general n-dimensional formula can be rewritten as
$$\frac{2^{\left\lceil\frac{d}{2}\right\rceil}\pi^{\left\lfloor\frac{d}{2}\right\rfloor} r^d}{d!!}$$
{            e# Begin block: stack holds d r
  1$_[2dP]*< e#   Build a list which repeats [2 pi] d times and take the first d elements
  f*         e#   Multiply each element of the list by r
  \,:)-2%    e#   Build a list [1 ... d] and take every other element starting at the end
  ./         e#   Pointwise divide. The d/2 elements of the longer list are untouched
  1+:*       e#   Add 1 to ensure the list is non-empty and multiply its elements
}

Groovy, 49 47 bytes + extra swag!
Edit: Saved 2 bytes thanks to @AlexRacer
A dyadic function - first argument is number of dimensions, second is the radius of the n-ball.
def v(n,r){n<1?1:n<2?2*r:6.2832*r*r*v(n-2,r)/n}
Recursive formula for the volume of an n-ball:
Vn=(2πr2Vn-2)⁄n
Dynamic Typing FTW!
My Scala and Java answers use the same logic, but with static typing so higher byte counts due to type annotations :(. However, Scala and Groovy allow me to omit the return and the semicolon, so that helps the byte count, unlike Java/C...

₊₁ for the extra SWAG!

Scala, 81 79 bytes + extra swag!
Edit: Saved 2 bytes thanks to @AlexRacer
A dyadic function - first argument is number of dimensions, second is the radius of the n-ball.
def v(n:Int,r:Float):Float=if n<1 1 else if n<2 2*r else 6.2832f*r*r*v(n-2,r)/n
Recursive formula for the volume of an n-ball:
Vn=(2πr2Vn-2)⁄n
Scala's lack of type inference for return types of recursive functions and function parameters and verbose ternary syntax hurts quite a bit here :(

Lithp, 96 characters + extra swag
Line split in 2 for readability:
#N,R::((if (< N 2) ((? (!= 0 N) (* 2 R) 1)) ((/ (* (* (* (* (f (- N 2) R) 2)
        3.1416) R) R) N))))

Thinking I need to upgrade my parser to require less spaces. Code size would be cut down nicely, especially in that ((/ (* (* (* (* section.
Usage:
% n-circle.lithp
(
    (def f #N,R::((if (< N 2) ((? (!= 0 N) (* 2 R) 1)) ((/ (* (* (* (* (f (- N 2) R) 2) 3.1416) R) R) N)))))
    (print (f 1 1))
    (print (f 2 3))
    (print (f 3 1))
    (print (f 3 4.5))
    (print (f 1 9.379))
    (print (f 0 48))
)

#./run.js n-circle.lithp
2
28.274333882308138
4.1887902047863905
381.7035074111598
18.758
1

Thanks to Rudolf for shaving a few bytes off.

What about shortening "3.141592653589793" to "3.1416", saving 11 bytes and still fitting into the rules?


text:
Add comments to a Python script and make it a bilingual Python/C++ “program”
Given the following Python 3 script:
def greet():
    print("Hello, world!")

greet()

Prepend some lines to this text file so that it can be both executed as a Python program as well as compiled and run as a C++ program producing the same output Hello, world! (including the newline at the end):
$ python3 bilingual.py.cpp
Hello, world!
$ g++ bilingual.py.cpp && ./a.out
Hello, world!

The solution will be scored by the count of non-whitespace characters of the entire program, including the Python script:
sed 's/\s//g' bilingual.py.cpp|wc -c

In the title you say add comments,  however in the body you say you only have to prepend some lines.  Which is it?

@WheatWizard The title is a hint. If you can solve this by prepending arbitrary lines (non-comments) I will be puzzled.

This is a very nice question. My only remark would be to just stick to the byte count for scoring in the future. It's simpler to check for those on different systems.

@Linus I admit that selecting the score in a non standard way was a mistake. Will not repeat it in the future.

Just a note: the provided sed command count the newlines, that are whitespace characters

Score 116
Prepend:
#include<cstdio>
#define print(A)main(){puts(A);}
#define greet()
#define \

The preprocessor backslash \ pulls the nasty : containing line into an unused macro. Try it here.
Thanks to edc65's answer for the note about implicit int in C++4.
Thanks to PieCot's answer for suggesting <cstdio> over <stdio.h>.
Thanks to Leon for suggest I remove the X in the original #define X\.

I don't have sed, if someone could verify my score I'd greatly appreciate it.

Removing all whitespace, my count (by hand) is 110 (but I was wrong... it's 111)

@Linus Why do you need the X in #define X\\?

@Leon good catch!

For anyone wondering what C++4 is: In this case it is short for "The C++ that gcc 4.3.2 accepts".

Score 119
(Thx @Linus for the byte count)
(1 byte saved thx @Conor O'Brien)
(1 byte saved thx @PieCot)
Counting bytes again by hand, I found 113. Maybe it's right this time. No it's not
#include <cstdio>
#define def main(){0?
#define print(x) puts(x);}
#define greet()

Notes: stdio and puts are still alive and kicking in C++. The missing int type is valid in C++ 4. Test

The score must be computed against the full program (including the python code).

Since the ternary conditional can have an empty second portion, you can remove the trailing 0 on line 2. Test.

OK I don't see why, as the python code will be the same for every answer, but you are the boss. I did the count by hand, not having sed, I hope it's right

@ConorO'Brien it really can! I did not know! Thx

You can use  rather than <stdio.h>

So I managed to get an online terminal working and sed 's/\s//g' leaves the newlines. This ends up being 119 characters.

Well if, sed leaves the newlines, that it's not count of non-whitespace characters, as newlines (like tabs, carriage return and the like) are whitespace characters. I keep my count

@Linus I changed my mind, and I'll use your count, even if it does not feel right. We need consistency

Score 131 130 134
The lines to be prepended are:
#import <iostream>
#define def int main(){0?
#define greet()
#define print(A) 0;std::cout<<A"\n";}

And the resulting code:
#import <iostream>
#define def int main(){0?
#define greet()
#define print(A) 0;std::cout<<A"\n";}
def greet():
    print("Hello, world!")

greet()

Testing
C:\Users\Conor O'Brien\Documents\Programming\golf
λ type bilingual.py.cpp

#import <iostream>
#define def int main(){0?
#define greet()
#define print(A) 0;std::cout<<A"\n";}
def greet():
    print("Hello, world!")

greet()
C:\Users\Conor O'Brien\Documents\Programming\golf
λ sed 's/\s//g' bilingual.py.cpp|wc -c
134

C:\Users\Conor O'Brien\Documents\Programming\golf
λ g++ bilingual.py.cpp 2>nul && a
Hello, world!

C:\Users\Conor O'Brien\Documents\Programming\golf
λ python bilingual.py.cpp
Hello, world!

C:\Users\Conor O'Brien\Documents\Programming\golf
λ

The output of the C++ version is not identical to the python version - it misses a newline. Added that clarification to the question.

@Leon This is now fixed.

#import is not valid C++

@Leon It may be deprecated but it is valid. It works in g++.

Clever handling of :

It is a deprecated gcc extension. g++ was used just as an example. The problem formulation requires a C++ program. And there is no sense arguing about that 1 char, since everyone will have to have that #include in their solution.

@Leon Our site rules say that if it works in one environment, it's a valid submission.

@Leon not everyone will have that #include, even if probably everyone will have some #include

@edc65 By that #include I meant the include as opposed to import.

Score 110 104
Improving upon Linus' answer:
#include <cstdio>
#define print main(){puts
#define greet() ;}//\
def greet():
    print("Hello, world!")

greet()

Test as C++
Test as Python

I have get 109...

@Linus I have a new line at the last line

Score 136
Only for the records:
#include <cstdio>
#define def class a{public
#define greet()
#define print(a) };int main(){puts(a);}

Another (less efficient) way to handle the colon.

But cstdio should be noted.

I think the score for this ends up being 136. You don't count the spaces.

@Linus: Thanks! I think you are right. If I use this command:
tr -d '[:space:] ' < bilingual.py.cpp | wc -c
I get 128, while this one:
tr -d '[:blank:] ' < bilingual.py.cpp | wc -c
provides 136

source: Stack Exchange

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

sort: votes


text:
Wait... what was I going to say again?
I often forget what I wanted to say when the teacher calls on me to speak. Can you make me a tool to solve this?
Requirements:

The program must loop as follows:

First, take in input
If the input is empty, print the last stored question.
Otherwise, store the input as a question.

Notes:

The input will never be empty if there are no questions stored.

Clarification: The program does not need to store multiple questions. I originally wanted it to store multiple, but I changed it after many people misunderstood the question.
Remember, this is code-golf, so the code with the smallest number of bytes wins.

Did you mean "previously stored question"? I find "last stored question" confusing as it suggests you might store more than one question.

@Neil It's supposed to be storing more than one question, but since many answers already misunderstood the question, I'll just leave it be.

Perl, 13 17 14 +1 = 15 bytes
/./?$;=$_:say$

+1 for the -n flag
(saved 4 bytes thanks to @Dada)
As long as the input is not equal to the carriage return, it stores the input in $;.  If it is equal to the carriage return, it prints what's already in $;.
This assumes that all input can be characterized as questions, even if grammatically, they are not such.

You probably wanted to write ne instead of eq (right now this doesn't work).

You can save three byte by doing /./ instead of $/ne$_ ;-)

05AB1E, 12 11 10 bytes
Thanks @daHugLenny and @Adnan for 1 byte!
Thanks @Emigna for 1 byte!
[IDõQiX,ëU

I can't test now, but I think you can remove the last character.

Yes, you can remove the last bracket (it will be auto-completed).

If you replace ® and © with X and U, you don't need the backslash.

Haskell, 49 bytes
g s=getLine>>=(#s)
""#s=putStr s>>g s
l#s=g l
g""

How it works: start  with g "". The parameter s of function g is the question in store. g reads the next line from stdin and passes it (and also s) to #. If the line is empty, # prints the store and calls g again. If the line is not empty, g is called with the line as the new store.

JavaScript, 36 34 31 bytes

for(;;b?a=b:alert(a))b=prompt()

An infinite loop keeps asking for input and stores it in b. It the input is not empty it's then stored in a, otherwise the value of a is printed.
Saved 2 bytes thanks to @ETHproductions

Nice answer. You can save a byte by removing the 1, and another by moving b?a=b:alert(a) into the last section within the for-loop (i.e. for(a=0;;b?a=b:alert(a))b=prompt())

In fact a=0 is not necessary neither. Since the input can only be empty if there are questions stored, a won't be referenced if it hasn't been assigned.

also stops the browser for a few seconds with firefox-49.0.2

@Oliver So what, the effect is the same. I could say old values remain stored in memory, just not referenced.

No, you need to be able to store multiple at once.

The only requirement in your question is that empty input prints the last stored question. Why do you want me to hold references to previously stored questions?

@bunyaCloven For me it only stops the browser when I tell it to block dialogs. That's expected due to the infinite loop. After some seconds the browser detects the problem and kills the JS.

yes but i couldn't manage to get out anyway

Mathematica, 44 bytes
If[(b=InputString[])=="",Print@a,a=b]~Do~∞

Full program. The Unicode character is U+221E INFINITY for \[Infinity].

Python 3, 31 bytes
while 1: I=input()or I;print(I)

Try it out!
-1 byte thanks to Flp.Tkc

you can write that while loop on 1 line

reticular, 12 bytes
id""E[$dp]~*

Try it online!
Explanation
id""E[$dp]~*
i             take a line of input     [input]
 d""E         push equality with ""    [input, input == ""]
     [$dp]    push that func           [input, input == "", [$p]]
         ~*   execute it iff equal
              on equal:
      $       drop empty input
       dp     duplicate then print the TOS
              this wraps around to the beginning, taking another line of input

Python3 - 49 bytes
s=""
while 1:
 b=input()
 if b:s=b
 else:print(s)

NameError: name 'b' is not defined

@shooqie Ah, I typed this with my phone so I accidentally left out b=input(). Thanks!

Pyke, 6 bytes
z=z~zr

Try it here!
     r - while 1:
z      -   input() or z.contents
 =z    -  z.contents = ^
   ~z  -  z.contents

Python 3, 34 bytes
s=""
while[print(s)]:s=input()or s

It doesn't? It works fine for me

The spec doesn't ask to store multiple questions?

Python 3, 60 bytes
q=[]
while 1:
 s=input()
 if''<s:q+=[s]
 else:print(q.pop())

CMD, 37 bytes
Sadly set does not take empty input:(
set/p a=
if %a%.=. echo b
set b=%a%
c

in a file names c.cmd or
set/p a=
if %a%.=. echo b
set b=%a%
%0

in any file. Working(Use - as empty):
set/p a=
if %a%.=-. echo b
set b=%a%
c

set/p will never make a variable empty, so at the very least you need set a= on the first line; also I think you mean set b=%a%.

C, 73 63 bytes
g(){char a[99],x;for(;;){gets(a);if(*a)x=*a;else*a=x,puts(a);}}

Only uses 1 buffer and a single char for handling the logic. If user inputs nothing, only the first char in the buffer gets overwritten by '\0', in that case it gets restored from x and printed, otherwise copy the first letter into x for later use.
Previous code:
main(){char a[99],b[99];for(;;){gets(a);if(*a)strcpy(b,a);else puts(b);}}

APLX, 19 bytes
a←⍞⋄→(0=⍴a)/1⋄a⋄→1

Explanation:
⍝ Note: the ⋄ symbols are statement separators, so I've replaced them here with newlines

a←⍞           ⍝ get an input string (⍞) and store it in variable a
→(0=⍴a)/1     ⍝ if the length of a (⍴a) is 0, goto (→) the start of this program (1)
a             ⍝ else, print a
→1            ⍝ goto the start of the program (1)

Java 7, 189 187 178 bytes..
class M{public static void main(String[]a){String s="",x;do{x=new java.util.Scanner(System.in).nextLine();if(x.isEmpty())System.out.println(s);else s=x;}while(1>0);}}

-9 bytes by using new java.util.Scanner directly, thanks to @cliffroot.
Probably the first time I used a do-while in a codegolf challenge..
When functions are allowed instead of programs, it's 135 bytes (still many times more than most other answers..)

this is a a bit shorter and seems to be working – void c(){for(String s="",x;(x=new java.util.Scanner(System.in).nextLine())!=null;)if(x.isEmpty())System.out.println(s);else s=x;}

@cliffroot Ummm.. aren't you missing a for or while somewhere?.. What is (x=new java.util.Scanner(System.in).nextLine())!=null;)?

Yeah, I managed to miss for before that somehow :)
it was supposed to be void c(){for(String s="",x;for(x=new java.util.Scanner(System.in).nextLine())!=null;)if(x.isEmpty())System.out.println(s);else s=x;} and it's actually 1 byte longer then the version with do-while is – void c(){String s="",x;do{x=new java.util.Scanner(System.in).nextLine();if(x.isEmpty())System.out.println(s);else s=x;}while(1>0);}

@cliffroot Ah of course.. thanks!

sed, 10 bytes
/./{x;d};g

Explanation:
      (implicit at start of program) read input, overwriting old input
/./{  If the input is nonempty
  x;  swap the input with the hold space
  d   then restart, without any implicit printing of input
};    end if statement
g     Append the hold space to the [empty] input
      (implicit at end of program) print the input, then restart

Nice to see an exoteric (i.e. "not esoteric") language tying with some of the golfing languages!

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


text:
Probability of All Combinations of Given Events
Given a sequences of events with probabilities between 0.0 and 1.0, generate and derive the probability of each combination occurring. You may presume that a sequence of numbers is provided in whatever construct your chosen language provides.
Here's an example; you may presume that the length of the sequence's combinations fit into memory:
{ 0.55, 0.67, 0.13 }

The program shall print each combination and the associated probability of that sequence occurring. A 1 shall denote that the event in that index of the input sequence occurred and a 0 shall denote that that event did not occur. The desired output is below (I don't care about printing the work, that's just for informational purposes of the algorithm):
[0,0,0] = (1 - 0.55) * (1-0.67) * (1-0.13) = 0.129195
[0,0,1] = (1 - 0.55) * (1-0.67) * (0.13)   = 0.019305
[0,1,0] = (1 - 0.55) * (0.67)   * (1-0.13) = 0.262305
[0,1,1] = (1 - 0.55) * (0.67)   * (0.13)   = 0.039195
[1,0,0] = (0.55)     * (1-0.67) * (1-0.13) = 0.157905
[1,0,1] = (0.55)     * (1-0.67) * (0.13)   = 0.023595
[1,1,0] = (0.55)     * (0.67)   * (1-0.13) = 0.320595
[1,1,1] = (0.55)     * (0.67)   * (0.13)   = 0.047905

This problem is tangentially related to calculating a "Cartesian product".
Remember, this is code-golf, so the code with the fewest number of bytes wins.

Welcome to Programming Puzzles & Code Golf, and nice first challenge!

Would [0.129195, 0.019305, 0.262305, ..., 0.047905] be enough as output or are the [0,0,0], [0,0,1], ... necessary?

@Laikoni That output is fine. The output portion isn't the meat of the problem.

Can the output be in reverse order?

@LuisMendo Sure, why not.

Haskell, 86 bytes
unlines.map(\p->show(fst<$>p)++" = "++show(product$snd<$>p)).mapM(\x->[(0,1-x),(1,x)])

Usage example:
Prelude> putStrLn $ unlines.map(\p->show(fst<$>p)++" = "++show(product$snd<$>p)).mapM(\x->[(0,1-x),(1,x)]) $ [0.55, 0.67, 0.13]
[0,0,0] = 0.12919499999999998
[0,0,1] = 1.9304999999999996e-2
[0,1,0] = 0.262305
[0,1,1] = 3.9195e-2
[1,0,0] = 0.157905
[1,0,1] = 2.3595e-2
[1,1,0] = 0.320595
[1,1,1] = 4.790500000000001e-2

Most of the bytes are spent for output formatting. If you are only interested in the probability vector it's only 29 bytes:
map product.mapM(\x->[1-x,x])

How it works:
                    mapM(\x->[(0,1-x),(1,x)])   -- for each number x in the input
                                                -- list make either the pair (0,1-x)
                                                -- or (1,x). Build a list with
                                                -- all combinations

    map(\p->                    )               -- for each such combination p
          show(fst<$>p)                         -- print the first elements
          ++" = "++                             -- then the string " = "
          show(product$snd<$>p)                 -- then the product of the second
                                                -- elements

unlines                                         -- joins with newlines

This is neat; I was curious if there was going to be a really short purely functional way of doing this. Do you happen to know C# or F#? I'm curious what the same algorithm in those languages would look like as I'm completely unfamiliar with the Haskell syntax.

@MarkJohnson: no, sorry I know neither C# nor F#.

Mathematica, 46 45 bytes
(s=#;1##&@@Abs[#-s]&/@{1,0}~Tuples~Length@s)&

Takes a list. Even works for the empty list {}, for which the output is {1}.
Test case:
%[{0.55, 0.67, 0.13}]
{0.129195, 0.019305, 0.262305, 0.039195, 0.157905, 0.023595, 0.320595, 0.047905}

Explanation
Given a list of probabilities s and a list of bits b with 0 denoting "did not occur" and 1 denoting "did occur", the list of probabilities to be multiplied is given by
1 - b - s

up to sign. If instead 0 denotes "did occur" and 1 "did not occur", then this simplifies to
b - s

so we:
                      {1,0}~Tuples~Length@s   (* Generate all possible bit combinations *)
              (#-s)&/@{1,0}~Tuples~Length@s   (* Generate probabilities to be multiplied
                                                  up to sign *)
     1##&@@Abs[#-s]&/@{1,0}~Tuples~Length@s   (* Correct sign and multiply;
                                                 1##& is short for Times *)
(s=#;1##&@@Abs[#-s]&/@{1,0}~Tuples~Length@s)& (* Assign s to first argument of function,
                                                 done separately to avoid clash
                                                 with inner function *)

MATL, 12 11 bytes
TF-|Z}&Z*!p

Input is a column vector, with the format [0.55; 0.67; 0.13]
Try it online!
TF    % Push [1, 0]
-     % Subtract from implicit input (column array), with broadcast. Gives a 2-col
      % matrix where the first column is the input minus 1 and the second is the input
|     % Absolute value
Z}    % Split the matrix into its rows
&Z*   % Cartesian product of all resulting. This gives a matrix as result, with each
      % "combination" on a different row
!p    % Product of each row. Implicitly display

Perl, 42 40 bytes
Includes +1 for -a
Give numbers on STDIN:
perl -M5.010 combi.pl <<< "0.55 0.67 0.13"

outputs
0.129195
0.019305
0.262305
0.039195
0.157905
0.023595
0.320595
0.047905

combi.pl:
#!/usr/bin/perl -a
$"=")\\*({1-,}";say eval for<({1-,}@F)>

Perl, 116 bytes
for(glob"{0,1}"x(@a=split/ /,<>)){@c=split//;$d=1;$d*=@c[$_]?$a[$_]:1-$a[$_]for 0..$#a;say"[".join(",",@c)."] = $d"}

Readable:
for(glob"{0,1}"x(@a=split/ /,<>)){
    @c=split//;
    $d=1;$d*=@c[$_]?$a[$_]:1-$a[$_]for 0..$#a;
    say"[".join(",",@c)."] = $d"
}

Creates a list of all possible combinations of 0s and 1s of length equal to the number of input parameters (e.g., for the example above, it would be of length 3), then calculates each probability.
Thanks to @Dada for showing me what the glob function can do, even though I'm not 100% sure I understand how it does that.
Sample output:
[0,0,0] = 0.129195
[0,0,1] = 0.019305
[0,1,0] = 0.262305
[0,1,1] = 0.039195
[1,0,0] = 0.157905
[1,0,1] = 0.023595
[1,1,0] = 0.320595
[1,1,1] = 0.047905

-a instead of (@a=split/ /,<>)...

R, 72 69 bytes
Takes input from stdin and returns an R-vector of probabilities.
apply(abs(t(expand.grid(rep(list(1:0),length(x<-scan())))-x)),1,prod)

Edit: Removed one unnecessary transpose, the permutation matrix is now the transposed version of the one below and the probabilities are calculated as the column-wise product rather than row-wise.
Example output:
[1] 0.129195 0.157905 0.262305 0.320595 0.019305 0.023595 0.039195 0.047905

Note that the probabilities are in a different order due to the fact that the permutation-matrix generated by expand.grid produces the following (generation of this matrix can probably be golfed using external packages):
1    1    1    1
2    0    1    1
3    1    0    1
4    0    0    1
5    1    1    0
6    0    1    0
7    1    0    0
8    0    0    0

The first probability corresponds to the inverted outcome of the first row in the above matrix and the second to the inverted second row etc. Formatting output to see this even more clearly makes the program longer (164 bytes):
m=expand.grid(rep(list(1:0),length(x<-scan())))
cat(paste0("[",apply(abs(m-1),1,function(x)paste0(x,collapse=",")),"] = ",apply(abs(t(t(m)-x)),1,prod),"\n"),sep="")

which instead produces:
[0,0,0] = 0.129195
[1,0,0] = 0.157905
[0,1,0] = 0.262305
[1,1,0] = 0.320595
[0,0,1] = 0.019305
[1,0,1] = 0.023595
[0,1,1] = 0.039195
[1,1,1] = 0.047905

I'd been working on my own answer to this but I couldn't come up with a neat solution. Great use of expand.grid! I think that apply can operate on data frames as well as matrices, so your code should work without the t(t(...)), which will save you 6 bytes.

@rturnbull Note that t is not related to any data frame but to allow the subtraction of the probability vector from the permutation matrix (with different dimensions). At least one of them is needed due to the way R handles these vectorized operations but I could probably remove the outer transpose and apply the product over columns instead. Will update tomorrow

J, 14 bytes
-.([:,*/)/@,.]

Usage
   f =: -.([:,*/)/@,.]
   f 0.55 0.67 0.13
0.129195 0.019305 0.262305 0.039195 0.157905 0.023595 0.320595 0.047905

Explanation
-.([:,*/)/@,.]  Input: array P
-.              Complement (1-x) for each x in P
             ]  Identity, get P
           ,.   Interleave to make pairs [(1-x), x]
  (     )/@     Reduce from right-to-left by
      */          Forming the multiplication table
   [:,            Flattening the result

Can you make |*//0.55 0.67 0.13-/0 1 into a train?

Jelly, 9 bytes
ż@C×þF¥@/

Try it online!

Pyth, 10 bytes
*MaVLQ^U2l

Try it online: Demonstration
Explanation:
*MaVLQ^U2lQ   implicit Q at the end (Q = input list)
      ^U2lQ   repeated Cartesian product of [0, 1] with itself length(Q)-times
              this gives all combinations of 0s and 1s
  aVLQ        absolute difference between these 0-1-vectors with Q
*M            fold the vectors by multiplication

JavaScript (Firefox 30-57), 57 bytes
f=([p,...a])=>1/p?[for(q of[1-p,p])for(b of f(a))q*b]:[1]

Returns an array of all the probabilities. If you want the array of events too, then for 86 bytes:
f=([p,...a])=>1/p?[for(e of'01')for(b of f(a))[[+e,...b[0]],(+e?p:1-p)*b[1]]]:[[[],1]]

If you're allowed the events as a string, then it's only 80 bytes:
f=([p,...a])=>1/p?[for(e of'01')for(b of f(a))[e+b[0],(+e?p:1-p)*b[1]]]:[['',1]]

Subtract two bytes for 1/ for each solution if the probability is never going to be zero.

How would you run this in a <script></script> block? I'm getting issues with the first "for" being unexpected?

@MarkJohnson As long as you're using Firefox 30 or later, it should just work.

C, 110 bytes
i,k;f(float* a,int n){for(k=0;k<1<<n;++k){float p=1;for(i=0;i<n;++i)p*=k&(1<<i)?a[i]:1-a[i];printf("%f,",p);}}

Ungolfed:
i,k;f(float* a,int n){
 for(k=0; k<1<<n; ++k){
  float p=1;
  for (i=0; i<n; ++i)
   p*=k&(1<<i)?a[i]:1-a[i];
  printf("%f,",p);
 }
}

Works up to 32 items, +5+1 bytes for 64 items (declare long k; and add L in the first loop so that k<1L<<N).

For >32 items, does C require the "L" literal on the *1*<<n or is that just a C++ thing?

@MarkJohnson yes i guess it would require.

05AB1E, 8 bytes
<Äæ¹æR+P

Try it online!
 <Äæ¹æR+P  # Main link (Input is [.1,.2])
 ###########
 <Ä        # Invert input, take the abs value.
           # Stack is [.9,.8]
   æ¹æ     # Powerset of both inverted and original arrays.
           # Stack is [[],[.1],[.2],[.1,.2]],[[],[.9],[.8],[.9,.8]]
      R+   # Reverse original array, add arrays together.
           # Stack is [.9,.8],[.1,.8],[.2,.9],[.1,.2]
        P  # For each sub array, push product.
           # Final Result: [0.02, 0.18, 0.08, 0.72]
           # E.G.          [  11,   10,   01,   00]

PHP, 105 97 94 93 87 bytes
for(;$i<2**$c=count($a=$argv)-$p=1;$i+=print-abs($p))for(;$c;)$p*=$a[$c--]-!($i>>$c&1);

Run like this:
php -r 'for(;$i<2**$c=count($a=$argv)-$p=1;$i+=print-abs($p))for(;$c;)$p*=$a[$c--]-!($i>>$c&1);' -- .55 .67 .13 2>/dev/null;echo
> -0.129195-0.157905-0.262305-0.320595-0.019305-0.023595-0.039195-0.047905

Note that the output is little endian:
[0,0,0]
[1,0,0]
[0,1,0]
[1,1,0]
[0,0,1]
[1,0,1]
[0,1,1]
[1,1,1]

Explanation
for(
  ;
  $i<2**$c=                 # Iterate over possible combinations: 2^c,
    count($a=$argv)-$p=1;   #   where c is input length -p (set p to 1)
  $i+=print-abs($p)         # Increment i and print product after each
)                           #   iteration, dash separated
  for(
     ;
     $c;                    # Iterate over input ($c..0)
  )
    $p*=                    # Multiply the product by difference between:
      $a[$c--]-             # - The $c-th item of the input.
      !($i>>$c&1);          # - The $c-th bit of `$i`, negated (1 or 0)

Tweaks

Saved 8 bytes by using binary logic to get bit instead of converting to string
Saved a byte by combining the resetting of $p to 1 with computation of $c
Saved a byte by adding the result of print (1) to $i instead of incrementing
Saved a byte by using underscore as output delimiter
Saved a byte by using minus sign as delimiter (there are no negative chances).
Saved 6 bytes by using $c instead of $$i

Perl 6, 24 19 bytes of Latin-1
{[*] 1 «-»@_ «|»@_}

Older code:
{[*] map {1-$^a|$^a},@_}

This is a function. Use it like this:
{[*] 1 «-»@_ «|»@_}(0.55, 0.67, 0.13)

to get:
any(any(any(0.129195, 0.019305), any(0.262305, 0.039195)), any(any(0.157905, 0.023595), any(0.320595, 0.047905)))

Explanation of the older code:
[*]          multiply together all array elements
map          but first transform each element via
{1-$^a|$^a}  considering both 1 minus the value and the value
,@_          of the function input

The newer code is basically the same, just using terser syntax:
[*]          multiply together all array elements
1 «-»@_      of the array formed by subtracting the argument from 1
«|»@_        pointwise considering both that and the original array

The map generates an array full of any constructs, which multiply into larger any constructs, neatly solving the problem without even needing a loop.
Not the shortest language for the program, but it's a very direct translation of the problem.

C++17, 137 131 129 bytes
Saving 6 bytes by declaring #define A auto, first time that such a short macro saves anything. -2 bytes for using #import and deleting the space before <
#import<iostream>
#define A auto
A g(A r){std::cout<<r<<",";}A g(A r,A x,A...p){g(x*r,p...);g(r-x*r,p...);}A f(A...p){g(1,p...);}

Spawns all possible combinations.
Ungolfed:
//base case to print the result
int g(auto r){std::cout << r << ",";}

//extract item from parameter pack
int g(auto r, auto x, auto... p) {
 g(x*r,p...);    //multiply with temp result and call with tail
 g(r-x*r,p...);  //same as above for (1-x)
}

//start of recursion, setting temp result to 1
int f(auto...p){g(1,p...);}

Usage:
f(0.55, 0.67, 0.13);

Dyalog APL, 10 bytes
New Solution
Index origin independent. Anonymous function. Takes probabilities list as argument.
∘.×/⊢,¨1-⊢

∘.×/ The Cartesian product reduction over
⊢ the argument values
,¨ each paired up with
1-⊢ the complement argument values (lit. one minus the argument values)
TryAPL online!

Old Solution
Requires ⎕IO←0 which is default on many systems. Prompts for probabilities' list.
|⎕∘.×.-⊂⍳2

Explanation
| absolute value of
⎕ the input, ɑ = [ɑ₁ ɑ₂ ɑ₃]
∘.×.- modified inner tensor multiplied, (ɑ₁ – b₁) ⊗ (ɑ₂ – b₂) ⊗ (ɑ₃ – b₃), with
⊂⍳2 the enclosed list b = [[0 1]]
Mathematical definition
As b is enclosed, it is scalar, and therefore extended to the length of ɑ, namely 3, so the entire expression is
 A = │(ɑ₁ – b) ⊗ (ɑ₂ – b) ⊗ (ɑ₃ – b)│ =
 │(ɑ₁ – [0,1]) ⊗ (ɑ₂ – [0,1]) ⊗ (ɑ₃ – [0,1])│ =
 │[ɑ₁,ɑ₁ – 1] ⊗ [ɑ₂, ɑ₂ – 1] ⊗ [ɑ₃,ɑ₃ – 1]│ =
 ⎢ ⎡ ⎡  ɑ₁ɑ₂ɑ₃  ⎤ ⎡  ɑ₁ɑ₂(ɑ₃-1)  ⎤ ⎤ ⎥
 ⎢ ⎢ ⎣  ɑ₁(ɑ₂-1)ɑ₃  ⎦ ⎣  ɑ₁(ɑ₂-1)(ɑ₃-1)  ⎦ ⎥ ⎥
 ⎢ ⎢ ⎡  (ɑ₁-1)ɑ₂ɑ₃  ⎤ ⎡  (ɑ₁-1)ɑ₂(ɑ₃-1)  ⎤ ⎥ ⎥
 ⎢ ⎣ ⎣(ɑ₁-1)(ɑ₂-1)ɑ₃⎦ ⎣(ɑ₁-1)(ɑ₂-1)(ɑ₃-1)⎦ ⎦ ⎥
TryAPL online!
Notes (applies to both old and new solution)
The program and formula works for any number (n) of variables, and returns an n-dimensional array of length 2 in every dimension. With three variables, the probability of a specific outcome
 P(p,q,r) = Ap,q,r
which can conveniently be selected from the array with (⊃A)[p;q;r] extracted with p q r⌷⊃A
E.g. 1 1 0⌷⊃|0.55 0.67 0.13∘.×.-⊂⍳2 gives P(55%,  67%, ¬13%) = 1.9305%