Professional Documents
Culture Documents
Initialization Expression
Test Expression
Increment/Decrement Expression
How does a For loop work?
7. The for loop has ended and the flow has gone
outside.
Example1
for(i=5;i>0;i--)
{
for(j=1;j<=i;j++)
{
System.out.print(j);
}
System.out.println();
}
}
}
Break and Continue
At times, after certain iterations, you need to
exit from the loop. To achieve this, Java
provides the break statement. The break
statement stops the execution of the remaining
statements within the body of the loop.
Syntax:
while (condition){
//code to be executed
Increment / decrement statement
}
How Does a While loop execute?
3. Condition is tested.
1. If Condition yields true, the flow goes into the Body.
2. If Condition yields false, the flow goes outside the loop
7. The while loop has ended and the flow has gone
outside.
// Java program to illustrate while loop
class WhileLoopDemo {
public static void main(String args[])
{
int x = 1, sum = 0;
5. Condition is tested.
1. If Condition yields true, go to Step 6.
2. If Condition yields false, the flow goes outside the
loop
do
{
System.out.println("value of x : " + x );
x++;
}while( x < 20 );
}
}
For-each (Enhanced) Loop
The Java for-each loop or enhanced for loop is
introduced since J2SE 5.0. It provides an
alternative approach to traverse the array or
collection in Java. It is mainly used to traverse
the array or collection elements. The advantage
of the for-each loop is that it eliminates the
possibility of bugs and makes the code more
readable. It is known as the for-each loop
because it traverses each element one by one.
labelname:
for(initialization; test-condition; incr/decr)
{
// code to be executed.
}
continue and break in Labelled loop
The continue and break statements can also be used with a label like
this:
Syntax:
continue labelname:
// It is called labelled continue statement.
// Here, labelname represents the name of loop.
Similarly,
break labelname:
// It is called labelled break statement.
package javaProgram;
public class LabelledLoopEx
{
public static void main(String[] args)
{
// Outer loop.
outer: for(int i = 1; i < 5; i++)
{
System.out.println(i);
// Inner loop.
for(int j = 1; j < 3; j++)
{
System.out.println(j);
if(i == j)
continue outer;
}
}
}
}
package javaProgram;
public class LabelledLoopEx2
{
public static void main(String[] args)
{
// Outer loop.
outer: for(int i = 1; i < 3; i++)
{
System.out.println("i: " +i);
// Inner loop.
int j = 1;
while(j < 3)
{
System.out.println("j: " +j);
int x = i + j;
if(x > 2)
break outer;
j++;
}
}
System.out.println("Jumping out of both labelled loops");
}
}