Introduction to For Loop
The for loop is especially useful for flow control when you already know how many times you need to execute the statements in the loop's block.
Syntax
for (initialization; boolean-expression; increment) {
statement(s)
}
For loop consists of following 3 parts:
- The initialization expression initializes the loop; it's executed once, as the loop begins.
- When the boolean-expression 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.
Example
1. /**
2. * @(#)ForLoopDemo.java
3. *
4. *
5. * @author
6. * @version 1.00 2009/11/11
7. */
8.
9. public class ForLoopDemo {
10.
11. /**
12. * Creates a new instance of ForLoopDemo.
13. */
14. public ForLoopDemo() {
15. }
16.
17. /**
18. * @param args the command line arguments
19. */
20. public static void main(String[] args) {
21. // TODO code application logic here
22.
23. for (int i=1; i<11; i++) {
24. System.out.println("Count is:" + i);
25.
26. }
27.
28.
29. }
30. }
Output
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
