 # Can somebody please explain this in detail to me?

## Recommended Posts int temp = 0;

int n = 4;

temp = (n < 2 ? 1 : n * factorial(n-1));    // I don't understand this at all

System.out.println(temp);

This is what I think:

Java checks if 4 < 2, and since it's not, it initiates the second expression in the ternary operator, and 'n' is multiplied by 'n-1'. So you get 4 x 3, and that value is assigned to 'temp'. So now, 'temp' holds 12. After that, Java checks if 'n' is less than 2, and since 3 is less than 2, 'temp' gets multiplied by 2, so you get 12 times 2 which is 24.

Thanks,

Noidlox

##### Share on other sites

^^^^^^^^^^ he wants explanation i think cuz thats the same thing as above haha

• 1
##### Share on other sites

do you know what a factorial is?

##### Share on other sites

"'n' is multiplied by 'n-1'" -- no, n is multiplied by factorial(n-1)

"Value is assigned to 'temp'" -- not really how recursive functions work, there is no "temporary" store in memory, but it is a temporary variable if you mean as such.

##### Share on other sites 19 hours ago, phony said:

do you know what a factorial is?

Yeah I do.

0! = 1

1! = 1

2! = 2

3! = 6

4! = 24

5! = 120

6! = 6 x 5 x 4 x 3 x 2 x 1

7! = 7 x 6 x 5 x 4 x 3 x 2 x 1

20 hours ago, Twisted Staff said:

^^^^^^^^^^ he wants explanation i think cuz thats the same thing as above haha

Rip English

##### Share on other sites

Ternary is a fancy if else.

temp = (n < 2 ? 1 : n * factorial(n-1));

Its the same as writing:

if(n < 2) {
temp = 1;
} else {
temp = n * factorial(n - 1);
}

You could also do something like : temp = (n % 2 ==1 ? ((n + 1 > 1) ? 0 : 1) : pow(n, 2)); - which are two if elses combined.

• 3
##### Share on other sites 6 hours ago, Alek said:

Ternary is a fancy if else.

temp = (n < 2 ? 1 : n * factorial(n-1));

Its the same as writing:

if(n < 2) {
temp = 1;
} else {
temp = n * factorial(n - 1);
}

You could also do something like : temp = (n % 2 ==1 ? ((n + 1 > 1) ? 0 : 1) : pow(n, 2)); - which are two if elses combined.

I had no idea you could combine two ternaries. It looks confusing as heck.

Thanks for the insight Alek!

## Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account. ×   Pasted as rich text.   Paste as plain text instead

Only 75 emoji are allowed.