0% found this document useful (0 votes)
2 views

Loops in Java

Uploaded by

Dhavan Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Loops in Java

Uploaded by

Dhavan Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

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
System.out.print(i+" ");
i++; // step value
}

1 10 20 30 40 50 60

int i=1; // start value


System.out.print(i+" ");
i--;
while(i<=500) { // 500 stop value
i=i+10;
System.out.print(i+" "); // step value
}

10 20 30 40 50 60

int i=10; // start value


while(i<=500) { // 500 stop value
System.out.print(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{
System.out.print(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++) {
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();
}

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++) {
System.out.print(" ");
}
for(int j=1;j<=i;j++){
System.out.print(j);
}
System.out.println();
}

You might also like