+ 4

Why is the output 4, can u explain ?

I'm always mistakening, don't want to remember, want to understand. If I understand, than I'll remember. Please give a link on these 2 ex. if they're already on sololearn. Random rand = new Random(); int x = rand.nextInt(5) %10; System.out.print(x); //Output 4 Thank you! private static int f(int i) { if(i<=1) return 1; else return(2+f(i-1)); //Here will be 4! and how 1 adds, from previous return 1 ? } public static void main(String[] a){ System.out.print(f(3)); // Outputs 5 ? }

25th Aug 2017, 11:36 AM
Val🐯
Val🐯 - avatar
1 Risposta
+ 6
if we run the f(3) step by step, f(3) = 2 + f(2) // will go to the else part f(3) = 2 + 2 + f(1) // again to the else part f(3) = 2 + 2 + 1 // hit the base condition f(3) = 5 !! Im not sure about the first question... the presence of random there indicates that x does not consistenly output 4. Though it just plays from 0 to 4...
25th Aug 2017, 12:14 PM
Joni Jimenez
Joni Jimenez - avatar