java - Does anyone know how to work this out? -
what output produced following program? answer says 7 have trouble working out.
public class practice { public static void main(string[] args){ int = 5; int b = g(i); system.out.println(b+i); } public static int f(int i) { int n = 0; while (n * n <= i) {n++;} return n-1; } public static int g(int a) { int b = 0; int j = f(a); b = b + j; return b; } }
i assume main getting called. here list of steps happen
g
gets called5
parameter.- then in function
g
,f
gets calledg
's parameter,5
- in function
f
n
set zero, while loop called , every timen*n
less or equal parameter, 5, n incremented. below outlines while loop.- 0*0 less 5, increment
n
0 1 , continue. - 1*1 less 5, increment
n
1 2 , continue. - 2*2 less 5, increment
n
2 3 , continue. - 3*3 not less 5, break out of loop.
- 0*0 less 5, increment
n-1
, 3-1=2, gets returned called, in variablej
in functiong
.b
gets assignedb+j
0+2
.b
gets returned variableb
in functionmain
.b+i
,5+2
, 7, gets printed answer.
Comments
Post a Comment