Thursday, 21 April 2011

Loops in java

For statements allow a set of statements to be repeated or looped through a fixed number of times. The round bracket contains initializer(s) ; conditional test ; incrementer(s). If more than one initializer or incrementer is used they are separated with commas. The test condition is checked prior to executing the block. Incrementing is done after executing the block. To output #1 #2 etc.(or #5 #4 etc.) on separate rows you could write:
for (int i=1;i<=5;i++) {document.writeln("#"+i);};
for (int i=5;i>=1;i--) {document.writeln("#"+i);};
Note: A special case of the for loop is the infinite loop for (;;){...}. This could be used with appropriate 'breakout' logic where a continuous operation was needed.
Caution: For loops can be written in ways that violate structured programming principles by allowing counter variables to be used outside of the scope of the loop block if they are defined outside the loop. Avoid the looseness of the language by always localizing the loop variable.
The enhanced for statement allows iteration over a full set of items or objects. For example:
int[] squares={0,1,4,9,16,25};
for (int square : squares) {...;}
// is equivalent to
for (int 1;i<squares.length;i++) {...;}
While statements allow a set of statements to be repeated or looped until a certain condition is met. The test condition is checked prior to executing the block. To output #1 #2 etc. on separate rows you could write:
int i=0;
while (i<=5) {
document.writeln("#"+i); i++;
};
Do While statements allow a set of statements to be repeated or looped until a certain condition is met. The test condition is checked after executing the block. To output #1 #2 etc. on separate rows you could write:
int i=1;
do {
document.writeln("#"+i); i++;
} while (i<=5);
Nested loops are possible. Be very careful about modifying any indices!.
for (int i=0;i<10;i++) {
for (int j=i;j<10;j++) {
System.out.print("*");}
System.out.println();}

No comments:

Post a Comment