Guest Posted May 7, 2017 Posted May 7, 2017 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
Twisted Staff Posted May 7, 2017 Posted May 7, 2017 ^^^^^^^^^^ he wants explanation i think cuz thats the same thing as above haha 1
Trees Posted May 7, 2017 Posted May 7, 2017 "'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.
Guest Posted May 7, 2017 Posted May 7, 2017 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
Alek Posted May 8, 2017 Posted May 8, 2017 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
Guest Posted May 8, 2017 Posted May 8, 2017 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!