Why does the following code execute six times? Please help me to understand how this works, as I've tried to get it into my head without success.
I thought it would first execute the code once, then increase count to 1, execute it a second time, increase count to 2, execute it a third time, increase count to 3, execute it a fourth time, increase count to 4, execute it a fifth time, increase count to 5, and then stop. Which means it will have executed the loop five times (for the first time, then for when count is 1, 2, 3, 4).
int count = 0;
do {
System.out.println("Welcome to Java!");
} while (count++ < 5);
Have you tried running this code?
int count = 0;
do {
System.out.println("Welcome to Java! " + count);
} while (count++ < 5);
output:
Welcome to Java! 0
Welcome to Java! 1
Welcome to Java! 2
Welcome to Java! 3
Welcome to Java! 4
Welcome to Java! 5
This should help you understand what is happening. Has others have said your confusion is most likely in how the post increment operator works.
To help you understand pre and post increment operators lets run another code sample
int a = 0;
int b = 0;
System.out.println("pre increment "+ ++a);
System.out.println("post increment "+ b++);
output:
pre increment 1
post increment 0
Summarizing: with post increment the expression is evaluated before the variable is incremented, with pre increment the expression is evaluated after the variable is incremented.
Its postfix operator so first evalution of whole expression then increment
Control will flow like this
0
Welcome to Java!
//condition check : 0 then 1
Welcome to Java!
//condition check : 1 then 2
Welcome to Java!
//condition check : 2 then 3
Welcome to Java!
//condition check : 3 then 4
Welcome to Java!
//condition check : 4 then 5
Welcome to Java!
//condition check : 5 then 6
That's because you're using post-increment. The while condition is first evaluated (with the count value from BEFORE the increment) and then count is incremented.
Try ++count (which first increments and then returns value).
edit:
Note that although using it in
for(int i = 0; i < n; i++) {}
is ok (it will usually get optimized, etc.),
for(int i = 0; i < n; ++i) {}
is a little bit better from the semantic point of view IMO.
It gets even more complicated in languages with operator overloading, where i++ can have different sideffects than ++i.
count++; // <-- would execute the above code 6 times
is post increment and
++count; // <-- would execute the above code 5 times
is pre increment
Consider:
while (count++ < 5) System.out.println(count); // prints 1 2 3 4 5
while (++count < 5) System.out.println(count); // prints 1 2 3 4
So your do...while executes first without a comparison (because of the do) then runs the comparison.
If it's pre-increment it could be re written like this:
int count = 0;
do {
// print
count = count + 1;
} while (count < 5)
If it's post-increment it could be re written like this:
int count = 0;
while (count < 5) {
// print statement
count = count + 1;
}
Related
So I'm working on Java Koans and I'm stuck on number 69. Here's the code:
#Koan
public void forLoopContinueLabel() {
int count = 0;
outerLabel:
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
count++;
if (count > 2) {
continue outerLabel;
}
}
count += 10;
}
// What does continue with a label mean?
// What gets executed? Where does the program flow continue?
assertEquals(count, __);
}
assertEquals checks if the answer is correct - it sends Koans both arguments and if they match you advance. For example, if one wrote assertEquals(3 + 3, 6) it would be correct.
The double-underscores mean REPLACE ME. In the Koans application it says that I need to replace the underscores with 8, but I don't understand exactly how the continue outerLabel works.
So my question is: Why is count 8?
Thanks in advance. Any help would be appreciated.
Only for i is 0 the j is 0, 1, 2.
For the remaining 5 i's only j is 0
1*3 + 5*1 = 8
Or
i j count
= = =====
0 0 0 count++
1 count++
1 2 count++
2 3 count++; continue outerLabel
1 0 4 count++; continue outerLabel
: : : :
5 0 8 count++; continue outerLabel
continue outerLabel; force to skip the second for.
Although the second for intends to iterate 6 times, it actually iterate only 3 times when i==0 and once for i>0.
I have been given "10 broken loops" to solve. I need to comment what was changed to make them correct.
I have
public class BrokenLoops {
//loop 5 times
public static void loop1() {
for (int i = 1; i != 10 ; i += 2) { //final statement i += 2 means i+2
System.out.println("In loop "+i);
}
System.out.println("Out of loop");
}
I know what the problem is, it will never be 10. 1 then 3 then 7 then 9 then 11 etc.
What I don't know is how many loops will be run if I type either !=9 or !=11
Would the code run as
If the code has !=11, would it run as
i = 1 "in loop"
1 = 3 "in loop"
i = 5 "in loop"
i = 7 "in loop"
i = 9 "in loop"
i = 11 "out of loop"
and so, there are 6 loops? The correct answer for 5 loops would be !=9?
Thanks in advance
This loop have condition to run when i is not equal 10. Because i starts at 1 and increases by 2 on every iteration, i will be always odd number and therefore can newer equal 10. So condition for loop will be always true. Simply put: your loop will go indefinitely.
About for statement from
The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows:
for (initialization; termination; increment) {
statement(s)
}
The initialization expression initializes the loop; it's executed once, as the loop begins.
The termination expression is invoked before each iteration. When it evaluates to false, the loop terminates.
The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.
More info about for statement: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
//edit
Correct code for 5 loops if you have to use '!=' comparison would be:
for(int i = 1; i != 11; i += 2)
// i==1 PASS
// i==3 PASS
// i==5 PASS
// i==7 PASS
// i==9 PASS
// i==11 FAILED, Loop ends here
although it's better to use
for(int i = 1; i < 10; i += 2)
//or
for(int i = 1; i < 11; i += 2)
this way, your loop will end after 5 loops and safer for many reasons
The loop as you have posted will run continuously as i will never get the value 10.
if you make the termination condition i != 9 then the loop will run for 4 times.
if you make the termination condition i != 11 then the loop will run for 5 times.
if you make the termination condition i <= 10 then the loop will run for 4 times.
to get it to run 10 times, change the for loop to this:
for (int i = 1; i <= 10; i++){
//Your code
}
EDIT:
Code:
for (int i = 1; i != 11; i += 2)
{
Console.WriteLine("In loop {0}", i);
}
Console.WriteLine("Out loop");
Console.ReadLine();
Output:
There are a few possible ways to solve your question.
Example 1
If you only need to get in the loop 5 times you can simple change your code to:
//loop 5 times
public static void loop1() {
for (int i = 0; i < 5 ; i++) {
System.out.println("In loop "+i);
}
System.out.println("Out of loop");
}
This will print something like:
In loop 0
In loop 1
In loop 2
In loop 3
In loop 4
Out of loop
Example 2
Another option would be to change your termination value to !=11(Just don't forget, that if you increment would become i += 3 for example, this will become an infinite loop again):
public static void loop1() {
for (int i = 1; i != 11 ; i += 2) { //final statement i += 2 means i+2
System.out.println("In loop "+i);
}
System.out.println("Out of loop");
}
This will terminate the loop once i will be equal to 11, so the output would be:
In loop 1
In loop 3
In loop 5
In loop 7
In loop 9
Out of loop
Example 3
You can also change termination to i < 10(or <=9 or <=10 or <11):
public static void loop1() {
for (int i = 1; i < 10 ; i += 2) { //final statement i += 2 means i+2
System.out.println("In loop "+i);
}
System.out.println("Out of loop");
}
The output will be same as in Example 2.
Example 4
You can also add a check inside your loop to stop it after something evaluates to true:
public static void loop1() {
int checkInt = 0;
for (int i = 1; i != 10 ; i += 2) { //final statement i += 2 means i+2
if (checkInt == 5) break;
System.out.println("In loop "+i);
checkInt++;
}
System.out.println("Out of loop");
}
So when checkInt will be equal to 5(loop was made 5 times), the loop will just stop. Output is the same as in Example 2 and Example 3
If the code has i !=11, would it run as
You just have to use i<10 to get the desired result
I understand how mostly everything works in a loop in Java but I came to a realization that I am failing to understand one thing which is The Order a Loop Operates.
Basically I am failing to understand this because of this simple but boggling piece of code that was displayed in my class, the code is displayed below.
public class Test {
public static void main (String[] args) {
int sum = 0;
for (int k = 1; k < 10; k += 2)
{
sum += k;
System.out.print(sum + " ");
}
}
}
The output the program puts out is 1 4 9 16 25
Now I understand how it repeats and spits out the numbers but how does it go about even creating 1. Now you can say it created 1 by taking k and adding it to sum but shouldn't k be equaling 3?
It goes k = 1; This sets k equal to 1. k < 10; Checks if k is less than 10. Then the question is when k += 2; Shouldn't k now equal to 3 but instead sum is now somehow equal to 1 after this operation occurred of adding 2 to 1, 2 + 1 = 3 but 3 + 0 = 1? How does this even go about.
My rationalizing for this is that any program I thought was to interpret code line by line or uniformly and not jumping around.
Overall my question is, how is sum equal to 1 when k is actually equal to 3.
The sections of the for loop are run at different times.
The first section is run once at the start to initialize the variables.
The second is run each time around the loop at the START of the loop to say whether to exit or not.
The final section is run each time around the loop at the END of the loop.
All sections are optional and can just be left blank if you want.
You can also depict a for loop as a while loop:
for (A;B;C) {
D;
}
is the same as:
A;
while (B) {
D;
C;
}
Let's step through your code:
We setup an int with initial value of 0 and assign it to sum.
We setup a for loop, setting int k = 1, and we will loop while k is less than 10, and after each iteration, 2 will be added to k.
So, the first iteration, k = 1. sum currently equals 0, so sum += k is actually 0 = 0 + 1 = 1. There's the 1 you are getting.
For the second iteration, k = 3. sum currently equals 1, so sum += k is actually 1 = 1 + 3 which is 4. There's the 4 that is showing up.
Repeat this for the rest of the loop!
In the first iteration of the loop, k=1. The k+=2 is only run at the beginning of the next iteration of the loop. The loop variable update condition (the last part of the for loop - i.e. the k+=2 part) never runs on the first iteration but does run on every other one, at the start. Therefore what you have is:
Iteration 1:
k=1
sum = 0 + 1; //so sum = 1
Iteration 2:
k=1+2 // so k=3
sum = 1 + 3 // so sum = 4
Iteration 3:
k=3+2 //k=5
sum = 4 + 5 //sum=9
etc...
It goes like this:
Initialize (k = 1)
Check condition (k < 10) (stop if false)
Run the code in the loop (sum += k and print)
Increment (k += 2)
Repeat from step 2
Following this logic, you get that 1 is printed first.
The last condition, k += 2 occurs after the first iteration of the loop.
So it's
k = 1, sum = 1
k = 3, sum = 4
k = 5, sum = 9
k = 7, sum = 16
k = 9, sum = 25
k is only incremented after the loop iteration. In general for any loop the values are updated after a loop iteration so k goes 1,3,5,7,9 and so the sum is correct.
Oh believe I had same problem. And you have to understand this quickly because when you are going to start doing bubble sort it will confuse you even more.
The thing you need to understand is that, its that it doesnt actually add +2 to 'k' until its done reading whats inside your 'for loop'
So this is how it starts, its starts with what you set 'k' for which is 1.
k = 1 is it less than 10? Yes, then do whats in the 'for loop' . Sum at first was initiated to 0. then in the first loop we add the value of k to whatever sum already has. So
sum = 0, k = 1. Therefore 0 +1 = 1. then next line ouput the value of sum with space. AND here is the IMPORTANT PART, it has now reach the end of the loop. So now it will add +2 to the value that k already has.
So k = 1 + 2 = 3. And now we start the second loop.
k=3, is less than 10? yes, ok do whats in for loop. add k to whatever value that sum already has. Sum is = 1 right ? and k is now equal to 3 right? So 3 + 1 = 4. And it display sum with a space and it has reach the end of the for loop so it add +2 to k that already has 3 in it which will equal to 5. and the loop continues.
oouff hope that helps! So remember it adds +2 at the end of the loop. Sorry if theres some typos typing from my samsung kinda annoying a bit cuz i have japanese keyboard...
Good luck!
has to
Let's break up your code. The keyword for just means loop. It will start # 1 and continue as long as k is less than 10. It will also increase by k+=2. To translate, it means k = k +2
Inside the loop sum = sum + k. It will then print the value that sum has plus a space.
k = 1, sum = 1
k = 3, sum = 4
k = 5, sum = 9
k = 7, sum = 16
k = 9, sum = 25
and keep repeating. Let me know if you still have trouble grasping this concept
int i = 1;
int j = 1;
while (i < 4) {
j += i;
i++;
}
System.out.println("i = " + i);
System.out.println("j = " + j);
I have the following above and I am trying to figure out how it works. I am new to java so I do not know how to debug my code yet. The output of this program says that i = 4 and j = 7. However the condition of the while loop should only execute when i < 4. Why does it execute when i = 4? I tried changing the condition to i <= 4 and it outputs i = 5. What am I missing here?
The loop counter will be incremented for every iteration through the loop. When the counter has been incremented past 3 (when it's equal to 4) the loop will stop. The loop won't run when the counter is 4, but the counter was still incremented to 4
i = 1
is 1 less than 4? Yes, so loop.
add one to i so now i = 2.
is 2 less than 4? Yes, so loop.
add one to i so now i = 3.
is 3 less than 4? Yes, so loop.
add one to i so now i = 4.
is 4 less than 4? No, leave the loop.
Print the value of i which is 4.
You enter the loop when i=3. Inside the loop, you increment i by 1 (i++). At the end of that iteration, you check if i<4, which it is not, because i=4.
Why does the following code
int i = 1;
System.out.print(i += i++);
System.out.print(i);
output 2 two times instead of 3 for the 2nd print?
Could somebody please shed some light on it?
Thanks.
If you realise that a++ works as follows (pseudocode):
func ++(ref a)
{
int b=a;
a=a+1;
return b;
}
then it all makes sense.
It may seems like i should be 3 in the end.
However, if you look into the statement more closely
i += (i++)
is equal to
i = ( i + (i++) )
which is, in this case, 1+1.
The side effect of i++ is i=i+1=1+1=2 as you may have expected, however, the value of i is override after the assignment.
I don't know the Java bytecode syntax very well yet but according to me at bytecode level your code would look something like this :
int i = 1; // iconst_1: variables { }, stack {1}
// istore_1: variables {1}, stack { }
i += i++; // iload_1: variables {1}, stack {1}
// iinc 1, 1: variables {2}, stack {1}
// iadd: variables {2}, stack {2} ...Note that here 1 gets added to the value on stack
// istore_1: variables {2}, stack {2} ...Here the variable value will overwrite the stack value
I think this explains the output you are getting pretty well. :-)
Experts, please correct me if I am wrong...
I don't think this is an issue with not knowing how the postfix unary operator (expr++) works. It is the order in which the statements are evaluated that is creating the confusion.
int i = 1;
System.out.println(i += i++); // Output: 2
So the last statement is the same as the following two statements in this order:
i++; // i is now 2 for the rest of this statement and the program
i = 1 + 1; // i is assigned again
So the postfix operator is evaluated first but then the whole line is evaluated but using the previous value of i.
So, to use another example that would make this more clear:
int i = 2;
System.out.println(i += i++); // Output: 4
System.out.println(i); // Output: 4
And another example:
int i = 2;
System.out.println(i = i + i++ + i--); // Output: 7
System.out.println(i); // Output: 7
The second line is assigning i. The first i is 2, the next i is also 2, but now the third i is 3 because i++ has changed the value of i. As the case from before, i-- will not have any affect on i because it will get rewritten with i = 2 + 2 + 3.
int i = 1;
System.out.println(i = i++ + i); // Output: 3
System.out.println(i); // Output: 3
1 + 1 == 2.
Therefore:
i + i == 2
and
i += i == 2
and then
i += i++ == 2
Pretty straight forward.