Jump to content

Can somebody please explain this in detail to me?


Recommended Posts

Posted

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

Posted
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

Posted

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.

  • Like 3
Posted
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!

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

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