Is the limit in the following loop (12332*324234) calculated once or every time the loop runs?
for(int i=0; i<12332*324234;i++)
{
//Do something!
}
There is no such limit. You can loop as many number of times you want.
An easy way to go about this would be to put the user-input prompt inside of a while loop, and only break out once you've verified that the grade is valid: Scanner scanner = new Scanner(System.in); int score; while (true) { System. out. print("Please enter score " + (g + 1) + ": "); score = scanner.
It do says that only one condition is allowed in a for loop, however you can add multiple conditions in for loop by using logical operators to connect them.
A loop will only execute while its condition is true. Since a for loop and a while loop both check the condition before the body is executed they will never execute if the condition is false.
For this it it calculated once, or more likely 0 times.
The compiler will optimize the multiplication away for you.
However this is not always the case if you have something like.
for(int i=0; i<someFunction();i++)
{
//Do something!
}
Because the compiler is not always able to see what someFunction
will return. So even if someFunction
does return a constant value every time, if the compiler doesn't know that, it cannot optimize it.
EDIT: As MainMa said in a comment, you are in this situation you can eliminate the cost by doing something like this:
int limit = someFunction();
for(int i=0; i<limit ;i++)
{
//Do something!
}
IF you are certain that the value of someFunction()
will not change during the loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With