Loop:
* process -> repeat
process -> execute -> one time
process
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
[Link](i+" ");
i++; // step value
}
1 10 20 30 40 50 60
int i=1; // start value
[Link](i+" ");
i--;
while(i<=500) { // 500 stop value
i=i+10;
[Link](i+" "); // step value
}
10 20 30 40 50 60
int i=10; // start value
while(i<=500) { // 500 stop value
[Link](i+" "); // step value
i=i+10;
do-while:
* exit controlled loop
* loop that checks the condition while leaving the block
* if condition is true, the repeat as long as condition is true
syntax:
do{
statements;
}while(condition);
ex:
int i=1;
do{
[Link](i+" ");
i++;
}while(i<=500);
for loop:
* in java you can delcare block level variables
* variables which are only of specific block or loop;
syntax:
for(initialization;condition;++/--) {
statements;
}
ex:
for(int i=1;i<=10;i++) {
[Link](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++){
[Link](j+" ");
}
[Link]();
}
step 1-> initialize i with 1
step 2 -> check the condition 1<=5 (T)
step 3 -> print value of i (1)
step 4 -> increase the value of i by 1 (i=2)
step 2-> check the condition 2<=5(T)
step 3-> 2
step 4-> i=3
step2 -> 3<=5(T)
step3 -> 3
setp4 -> i=4
step2 -> 4<=5(T)
step3 -> 4
step4 -> i=5
step2 -> 5<=5(T)
step3 -> 5
step4 -> i=6
step2 -> 6<=5(F)
for(int i=1;i<=5;i++) {
for(int j=1;j<5-i+1;j++) {
[Link](" ");
}
for(int j=1;j<=i;j++){
[Link](j);
}
[Link]();
}