Jump to content
Guest

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

Link to comment
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

Link to comment
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!

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...