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
⌛
This post has been reserved for your question.
Hey @°~°! Please useTIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here./close
or theClose 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.
Please format your code to make it more readable. For java, it should look like this:
i get the whole for and while loop stuff but i dont get that part
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.
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
💤
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.