I have this simple code sample that I don't understand.
// Compute integer powers of 2.
class Power {
public static void main (String args[]) {
int e, result;
for (int i = 0; i < 10; i++) {
result = 1;
e = i;
while (e > 0) {
result *= 2;
e--;
}
System.out.println("2 to the " + i + " power is " + result);
}
}
}
Producing this output.
2 to the 0 power is 1
2 to the 1 power is 2
2 to the 2 power is 4
2 to the 3 power is 8
2 to the 4 power is 16
2 to the 5 power is 32
2 to the 6 power is 64
2 to the 7 power is 128
2 to the 8 power is 256
2 to the 9 power is 512
Questions:
How come result is not always 2, since it's being re-initialized every time the for loop is entered?
The e-- decrement doesn't do a thing either, does it? Since, again, e is being set equal to i afresh on every iteration.
Thanks.
How come result is not always 2, since it's being re-initialized every
time the for loop is entered?
Yes, it is being re-initialized but only in the first loop. Your inner loop is looping while(e > 0) and double result at each iteration. Then once you are done looping, you pring the result and restart. The value of result will depend on e which define the number of times result is doubled.
The e-- decrement doesn't do a thing either, does it? Since, again, e
is being set equal to i afresh on every iteration.
Again, yes it is being set back to i at each iteration but that doesn't mean it is useless. At each iteration, e is set back to the new value of i, and then you use it to create an inner loop while e > 0 where at each iteration you decrement e of 1 and double the result.
The two questions kind of go together.
You see, e is set to i which is actually INCREASED each iteration.
And the higher e is, the more often the inner while will be worked through.
So for example in your 3rd for iteration
i = 2
e = 2
result = 1
So first while:
result = result*2 = 1*2 = 2
e = 1
e is still > 0 so after the second while:
result = result*2 = 2*2 = 4
e = 0
And there we go.
e-- did something twice and result is NOT 2.
result and e are re-initialized at the top of the for loop, but are modified within the while loop before result is displayed at the bottom of the for loop.
Related
public class Main {
public static void main(String[] args) {
int e;
int result;
for(int i =0; i <10; i++){
result = 1;
e = i;
while(e > 0){
result *= 2;
e--;
}
System.out.println("2 to the " + i + " power is " + result);
}
}
}
I am going through Java, A Beginner's Guide, by Herbert Schildt. I am unclear on the above code. When i is set to zero on the first iteration, the while statement is skipped because e will be set to zero and the while condition will not be true. Thus i will be 1 and result will be 1 and this answer will be printed out.
In the second iteration, i and e will be 1, thus the while statement will be executed because e > 1 and the result will therefore be 2. So far, so good. However, e is decremented by 1 after the result is calculated so now e is back to 0.
The third iteration where i is set to 2 is where I am getting lost. Since e is now zero again, what happens on this iteration? Doesn't the program get kicked out of the while loop and go back to the beginning again since the while condition is no longer true? If so, doesn't result get set back to 1, which will have result being equal to 2 again instead of 4 after the while loop for i = 2 is run?
I understand the program in all subsequent iterations of i since e will not be set back to zero again after it gets past this third iteration. But I'm confused as to why the cumulative result isn't lost as a consequence of decrementing e back to zero after the second iteration.
Thanks for the help.
The while cycle is inside the for cycle. Let's study the while cycle first. It will multiply result with 2 and decrement e while e is bigger than 0, essentially, the result will be
initial value * 2^i
now, the for cycle goes from 0 to 10 and in each iteration initializes result with 1 and e with i (the power). It will calculate 2^i in each iteration except the very first, where i is 0 and therefore e>0 will be false. And the iteration will println the result in the end.
When i is set to zero on the first iteration, the while statement is
skipped because e will be set to zero and the while condition will not
be true.
That's correct.
In the second iteration, i and e will be 1, thus the while statement
will be executed because e > 1 and the result will therefore be 2. So
far, so good. However, e is decremented by 1 after the result is
calculated so now e is back to 0.
That's correct (if you meant e > 0 there).
The third iteration where i is set to 2 is where I am getting lost.
Since e is now zero again, what happens on this iteration? Doesn't the
program get kicked out of the while loop and go back to the beginning
again since the while condition is no longer true? If so, doesn't
result get set back to 1, which will have result being equal to 2
again instead of 4 after the while loop for i = 2 is run?
Incorrect. e is 0 indeed, but only until the line of
e = i;
where the value of i, which is 2 will be assigned to e. So e will be 2 at the start of the while loop and the while condition will be true twice, therefore you will have two iterations for the while loop.
I understand the program in all subsequent iterations of i since e
will not be set back to zero again after it gets past this third
iteration. But I'm confused as to why the cumulative result isn't lost
as a consequence of decrementing e back to zero after the second
iteration.
Incorrect. e will be 0 at the end of each iteration of the while loop, but it will be i before each while loop.
In the second iteration, i and e will be 1, thus the while statement
will be executed because e > 1 and the result will therefore be 2. So
far, so good. However, e is decremented by 1 after the result is
calculated so now e is back to 0.
Because e > 0, but apart from that, this is exactly right.
The third iteration where i is set to 2 is where I am getting lost.
Since e is now zero again, what happens on this iteration?
for(int i =0; i <10; i++){
result = 1;
e = i;
while(e > 0){
result *= 2;
e--;
}
System.out.println("2 to the " + i + " power is " + result);
}
You're correct in thinking that after the second iteration of the for loop, e will be 0. But there's this beautiful line at the beginning: e = i;
In the third iteration, i will be 2, which means after e = i (and right before the while), e will be set to 2. Not 0.
So i was getting this program in my book and tested it, it worked fine. I need help though understanding how it excactly works. I know the power of two means for example 2x2x2x2x2x2x2x2x2 = 512. Well, here is the program:
// Compute integer powers of 2.
class Power {
public static void main(String args[]) {
int e;
int result;
for(int i=0; i < 10; i++) {
result = 1;
e = i;
while(e > 0) {
result *= 2;
e--;
}
System.out.println("2 to the " + i + " power is " + result);
}
}
}
So i've learned that result *=2 means: result = result * 2. I don't get how this works. Example, i is now 4. Result = 1 again, e=i, so e is now 4. 4 is higher than 0, so the while loop runs. Then it say's result is result * 2, but that's 1=1 * 2 = 2. But the result should be 16. How does result changes here to 16? Because it is 1 all the time. I don't get it. Also, why the e-- part? I've tried the program with e++, but then it prints result as 1 and after this only 0. Also tried it without e-- or e++ at all, but then it freezes in the dos-prompt. Please note that i am a beginner and this is my first while loop. Any help i would appreciate.
while(e > 0) {
result * = 2;
e--;
}
this loop executes untill the e becomes zero.
so in first loop
result = 1 * 2;
in second loop
result = result * 2; means result = 2 * 2
likewise.
You are using nested loops. That is, a while loop inside a for loop. This means that for every iteration of for loop, while loop will execute until it's condition becomes false.
Now coming to your questions, for first iteration of for, i = 0. Which means that e = 0, which in-turn means that while loop will not execute. So, result is 1 here, which is logical since any n^0 = 1.
For second iteration of for, i = 1. Which means that e = 1. Here, while loop will run for 1 iteration. It will make result = 2 (result *= 2). So, result is 2 because 2^1 = 2.
Below is the dry-run table.
for i 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 so on. This table seems ugly, but it will give you a hint.
How does result changes here to 16? Because it is 1 all the time.
Result is only initialized with 1, but it's value is multiplied each time while loop executes.
I've tried the program with e++, but then it prints result as 1 and
after this only 0.
If you put e++ instead of e--, this loop will run until e overflows. But as soon value of e reaches 33, result will become 0 due to multiplication. And after that, it will remain 0.
Also tried it without e-- or e++ at all, but then it freezes in the
dos-prompt.
It means that your condition of while loop will never become false, and hence, it will be an infinite loop.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
What output is produced by the following program?
The answer says 7 but i have trouble working it out.
public class practice {
public static void main(String[] args){
int i = 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 is getting called. Here is a list of steps that happen
g gets called with 5 as its parameter.
then in function g, f gets called with g's parameter, which is 5
In function f n is set to zero, a while loop is called and every time n*n is less than or equal to its parameter, which is 5, n is incremented. below outlines the while loop.
0*0 is less than 5, increment n from 0 to 1 and continue.
1*1 is less than 5, increment n from 1 to 2 and continue.
2*2 is less than 5, increment n from 2 to 3 and continue.
3*3 is not less than 5, break out of the loop.
n-1, which is 3-1=2, gets returned back to where it was called, in variable j in function g.
b gets assigned to b+j which is 0+2.
b gets returned back to variable b in function main.
b+i, which is 5+2, which is 7, gets printed as the answer.
Your using a number (5) and basically checking what is the first whole number squared that equals more than than 5. Then you negate 1 from the answer and add 5.
So here is the maths:
1. Find the first whole number squared that is larger than 5
0*0 = 0 //+1
1*1 = 1 //+1
2*2 = 4 //+1
3*3 = 9 //3*3 is the first value over 5; loop breaks
2. Negate 1 from 3 (the first whole number when squared that is larger than
3 - 1 = 2; //using 3, negate 1 (also could have used n--)
3. Using the final value 2 add 5
2 + 5 = 7 //using 2 add 5
Answer is 7.
There is some really unnecessary stuff in this code, such as the two extra methods.
Our teacher in my AP Computer Science course gave us this code
final int LIMIT = 5;
int i, count;
for (count=1; count<=LIMIT; count++)
{
for (i=0; i<count; i++)
{
System.out.print(count);
}
}
System.out.println();
When this code executes, the output is as follows
1
22
333
4444
55555
I do not have a good understanding of the for statement and I cannot understand why the code would print 1 once, 2 twice, 3 three times, ect. Can someone please try to explain this to me?
This is a great question and covers the basics of for loops.
Thinking About For Loops: The Basics
Think about the code you have written above in this way:
A for loop does ("executes") what is enclosed in its body once for each time you specify - or, to think about it another way, until a condition that you specify is false. As the coder, you need to tell the program: [1] at what point to begin; [2] how many times to do it (better thought about as "until when to do it"); [3] and by how many the code should "count" (what we call "increment").
To demonstrate with pseudo-code:
for ([1]; [2]; [3])
or
for (where to begin; how many times; how to count) {
// DO SOMETHING
}
Remember, as you "count", you are increasing - in the case of the first for loop - the count variable by the how to count piece (count + how to count). What you have in your above code is a nested for loop - a loop inside another loop (described, below). Referencing the pseudo-code I have written, above, your first for loop does the following:
for (start counting at 1; iterate once until count is greater than 5; increment count by 1)
Your Question
Now, comes the piece that is throwing you. You have two variables to pay attention to because you have two for loops: count, in the first for loop (used by the second); i in the second. Each time your first for loop iterates, the first for loop must execute the second for loop (look at your code). Again, pay attention to the two variables - but, more importantly, the relationship between the variables in both for loops' conditions. The second for loop depends upon the first. Think about it this way:
As count is incremented (here, increased by one), the second for loop must execute its own operation that many times:
for (i starting at 0; i not equal to count; increment by 1)
So, at the first iteration you would see something like this:
for (count = 1; count will always iterate once until condition false; increment){ }
for (i = 0; i < count (1); increment i){ }
Result will be:
1
Then the first loop is incremented (count becomes 2) and you get:
for (i = 0; i < (2); increment i)
Because the second loop will iterate until i is no longer less than 2 (not including 2), your result will be:
22
This relationship will continue until you get your final result:
55555
A Final Comment
Your teacher is looking to teach you a few different things with the code you provided, above, namely two: nested for loops; and how initializing your iterator (i and count) and the condition statement <, >, <=, >=, etc.) affects the behavior of a loop.
The first for loop indicates that it will loop the contents LIMIT times(which is 5), incrementing count by 1 at the end of each loop. The second inner for loop indicates that number of times to print the number count.
Might be easier to understand with indentation of your code:
final int LIMIT = 5;
int i, count;
for (count=1; count<=LIMIT; count++) {
for (i=0; i<count; i++) {
System.out.print(count);
}
System.out.println();
}
The first for loop starts at 1 and ends at limit 5. The inner loop starts at 0 and goes to the current count. So for the first iteration the inner loop will go from 0 to 1. This will print count 1 time which count is 1. The second time through the outer loop the counter will be 2 so the inner loop will loop from 0 to 2. It will print 2 twice. The 3rd time through count will be 3. The inner loop will loop from 0 to 3 and print 3 3 times. Etc... This is nested looping.
The first loop will write 5 lines as LIMIT = 5
The second loop will write n times the current index of the first loop, for each line.
n equals the current index of the first loop. So line #1, one time 1, line #2, two times 2, ....
You have two for loops, the outer loop starts count with a value of 1 and will iterate until count has a value greater than 5. The inner for loop will start with a value of 0 and will iterate until i has a value greater than or equal to count. So,
count <- 1
i <- 0
while (i < count) { print(count); i++; } // <-- 0 to 1 is a range of 1
newline();
Then
count <- 2
i <- 0
while (i < count) { print(count); i++; } // <-- 0 to 2 is a range of 2
newline();
And so on.
It is probably best to explain this by walking through the steps on by one...
final int LIMIT = 5;
int i, count;
for (count=1; count<=LIMIT; count++)
{
for (i=0; i<count; i++)
{
System.out.print(count);
}
System.out.println(); //from the results you are getting, this statement should be here
}
To put this in human readable terms:
A. we have a number LIMIT that is 5
B. we have a number i and count
C. set the number count to 1
D. if the number count is less than LIMIT, do the following:
1. set the number i to 0
2. if the number i is less than the number count, do the following:
a. print out the number count
b. add 1 to the number i
c. go back to step 2
3. print out an empty line
4. add 1 to the number count
5. go back to step D
So, if we go through the loops, here's what our variables become:
count is set to 1
count is less than 5
i is set to 0
i is less than count? yes, i is 0 and count is 1
print out the value of count (which is 1)
add 1 to i
i is 1
is i less than count? no, i is 1 and count is 1
print out a new line
add 1 to count
count is 2
count is less than 5
i is set to 0
i is less than count? yes, i is 0 and count is 2
print out the value of count (which is 2)
add 1 to i
is i less than count? yes, i is 1 and count is 2
print out the value of count (which is 2)
add 1 to i
is i less than count? no, i is 2 and count is 2
print out a new line
add 1 to count
count is 3
etc.
This continues until count is greater than 5, at which point it exists. As you can see from the pattern, the variable count determines which number gets printed, and the variable i determines how many times it is printed.
We've got 2 pieces of code:
int a = 3;
while (a <= n) {
a = a * a;
}
And:
public void foo(int n, int m) {
int i = m;
while (i > 100)
i = i / 3;
for (int k = i ; k >= 0; k--) {
for (int j = 1; j < n; j*=2)
System.out.print(k + "\t" + j);
System.out.println();
}
}
What is the time complexity of them?
I think that the first one is: O(logn), because it's progressing to N with power of 2.
So maybe it's O(log2n) ?
And the second one I believe is: O(nlog2n), because it's progressing with jumps of 2, and also running on the outer loop.
Am I right?
I believe, that first code will run in O(Log(LogN)) time. It's simple to understand in this way
Before first iteration you have 3 in power 1
After first iteration you have 3 in power 2
After second iteration you have 3 in power 4
After third iteration you have 3 in power 8
After fourth iteration you have 3 in power 16
and so on.
In the second code first piece of code will work in O(LogM) time, because you divide i by 3 every time. The second piece of code C times (C equals 100 in your case) will perform O(LogN) operations, because you multiply j by 2 every time, so it runs in O(CLogN), and you have complexity O(LogM + CLogN)
For the first one, it is indeed O(log(log(n))). Thanks to #MarounMaroun for the hint, I could find this:
l(k) = l(k-1)^2
l(0) = 3
Solving this system yields:
l(k) = 3^(2^k)
So, we are looking for such a k that satisfies l(k) = n. So simply solve that:
This means we found:
The second code is seems misleading. It looks like O(nlog(n)), but the outer loop limited to 100. So, if m < 100, then it obviously is O(mlog(n)). Otherwise, it kind of depends on where exactly m is. Consider these two:
m: 305 -> 101 -> 33
m: 300 -> 100
In the first case, the outer loop would run 33 times. Whereas the second case would cause 100 iterations. I'm not sure, but I think you can write this as being O(log(n)).