CATEGORII DOCUMENTE |
Asp | Autocad | C | Dot net | Excel | Fox pro | Html | Java |
Linux | Mathcad | Photoshop | Php | Sql | Visual studio | Windows | Xml |
Inside the body of any of the iteration statements you can also control the flow of the loop by using break and continue. break quits the loop without executing the rest of the statements in the loop. continue stops the execution of the current iteration and goes back to the beginning of the loop to begin a new iteration.
This program shows examples of break and continue within for and while loops:
//: BreakAndContinue.java
// Demonstrates break and continue keywords
public class BreakAndContinue
int i = 0;
// An 'infinite loop':
while(true)
}
In the for loop the value of i never gets to 100 because the break statement breaks out of the loop when i is 74. Normally, you'd use a break like this only if you didn't know when the terminating condition was going to occur. The continue statement causes execution to go back to the top of the iteration loop (thus incrementing i) whenever i is not evenly divisible by 9. When it is, the value is printed.
The second portion shows an "infinite loop" that would, in theory, continue forever. However, inside the loop there is a break statement that will break out of the loop. In addition, you'll see that the continue moves back to the top of the loop without completing the remainder. (Thus printing happens only when the value of i is divisible by 9.) The output is:
The value 0 is printed because 0 % 9 produces 0.
A second form of the infinite loop is for(;;). The compiler treats both while(true) and for(;;) in the same way so whichever one you use is a matter of programming taste.
Politica de confidentialitate | Termeni si conditii de utilizare |
Vizualizari: 604
Importanta:
Termeni si conditii de utilizare | Contact
© SCRIGROUP 2024 . All rights reserved