quick help with a simple confusion

int result = 0; for (int i = 0; i < 4; i++) { result += 3; } System.out.println(result); vs int result = 0; int i = 0; while (true) { result += 3; // shorthand for result = result + 3 i++; // shorthand for i = i + 1 if (i == 4) { break; } } System.out.println(result); why in the first one when we use i < 4 it prints out 12 but in the second one i == 4 prints out the same thing
6 Replies
JavaBot
JavaBot2mo ago
This post has been reserved for your question.
Hey @°~°! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically marked as dormant after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
JavaBot
JavaBot2mo ago
Please format your code to make it more readable. For java, it should look like this:
​`​`​`​java
public void foo() {

}
​`​`​`​
​`​`​`​java
public void foo() {

}
​`​`​`​
°~°
°~°OP2mo ago
i get the whole for and while loop stuff but i dont get that part
stechy1
stechy12mo ago
Hi, it is about condition, when to break the loop. In the for cycle, the condition is "i<4" but in the while loop you have "i==4". And also the difference is when you increase the "i" variable.
tjoener
tjoener2mo ago
If you put the i == 4 break at the beginning of the while loop it should print 9 for loops check the condition before doing another iteration, you check it after with the while loop
JavaBot
JavaBot2mo ago
💤 Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived. If your question was not answered yet, feel free to re-open this post or create a new one. In case your post is not getting any attention, you can try to use /help ping. Warning: abusing this will result in moderative actions taken against you.

Did you find this page helpful?