Integer powers program Java help needed -
so getting program in book , tested it, worked fine. need though understanding how excactly works. know power of 2 means example 2x2x2x2x2x2x2x2x2 = 512. well, here program:
// compute integer powers of 2. class power { public static void main(string args[]) { int e; int result; for(int i=0; < 10; i++) { result = 1; e = i; while(e > 0) { result *= 2; e--; } system.out.println("2 " + + " power " + result); } } }
so i've learned result *=2 means: result = result * 2. don't how works. example, 4. result = 1 again, e=i, e 4. 4 higher 0, while loop runs. say's result result * 2, that's 1=1 * 2 = 2. result should 16. how result changes here 16? because 1 time. don't it. also, why e-- part? i've tried program e++, prints result 1 , after 0. tried without e-- or e++ @ all, freezes in dos-prompt. please note beginner , first while loop. appreciate.
you using nested loops. is, while
loop inside for
loop. means every iteration of for
loop, while
loop execute until it's condition becomes false.
now coming questions, first iteration of for
, = 0. means e = 0, in-turn means while
loop not execute. so, result 1 here, logical since n^0 = 1.
for second iteration of for
, = 1. means e = 1. here, while
loop run 1 iteration. make result = 2 (result *= 2). so, result 2 because 2^1 = 2.
below dry-run table.
for while e result loop loop 1 0 1 0 1 2 1 1 1 2 3 2 1 2 2 1 2 1 4 4 3 1 3 2 2 2 2 4 1 3 1 8
and on. table seems ugly, give hint.
how result changes here 16? because 1 time.
result only initialized 1, it's value multiplied each time while
loop executes.
i've tried program e++, prints result 1 , after 0.
if put e++
instead of e--
, loop run until e overflows. value of e reaches 33, result become 0 due multiplication. , after that, remain 0.
also tried without e-- or e++ @ all, freezes in dos-prompt.
it means condition of while loop never become false, , hence, infinite loop.
Comments
Post a Comment