Loops in Java
Loops in Java
while loop:
*Entry controlled loop
* test the condition before executing the block
* execute the loop when condition is true
and repeat until condition is false.
syntax:
while(condition){
statements;
}
ex:
int i=1; // start value
while(i<=500) { // 500 stop value
System.out.print(i+" ");
i++; // step value
}
1 10 20 30 40 50 60
10 20 30 40 50 60
do-while:
syntax:
do{
statements;
}while(condition);
ex:
int i=1;
do{
System.out.print(i+" ");
i++;
}while(i<=500);
for loop:
syntax:
for(initialization;condition;++/--) {
statements;
}
ex:
for(int i=1;i<=10;i++) {
System.out.println(i);
}
i is block level variable should used in block executed by the that for loop only
Nested loops:
* loop inside of another loop
* best loop as nested loop, for
* to repeat execution of a loop
ex:
for(int i=1;i<=5;i++) {
for(int j=1;j<=5;j++){
System.out.print(j+" ");
}
System.out.println();
}
for(int i=1;i<=5;i++) {
for(int j=1;j<5-i+1;j++) {
System.out.print(" ");
}
for(int j=1;j<=i;j++){
System.out.print(j);
}
System.out.println();
}