You are on page 1of 24

Working with Loop Constructs

In computer programming, loops are used to


repeat a block of code. A looping statement
enables you to execute the same statements for
a certain number of times.

For this, you do not need to write the


statements repeatedly. You can enclose the
statements within the loop construct and the
loop construct executes the statements till the
specified condition is met. Java supports the
following loop constructs:

The for loop


The while loop
The do…while loop
The for each loop
The labelled loop
Using the for Construct
A for loop is a repetition control structure that
allows you to efficiently write a loop that needs
to be executed a specific number of times.
A for loop is useful when you know how many
times a task is to be repeated.
Syntax: For Loop
for (initialization expr; test expr; increment/Decrement exp)
{
// body of the loop
// statements we want to execute
}

Parts of Java For Loop

Java for loop is divided into various parts as mentioned


below:

 Initialization Expression
 Test Expression
 Increment/Decrement Expression
How does a For loop work?

Control falls into the for loop.


1. Initialization is done

2. The flow jumps to Condition


3. Condition is tested.
1. If the Condition yields true, the flow goes into the Body
2. If the Condition yields false, the flow goes outside the
loop

4. The statements inside the body of the loop get


executed.

5. The flow goes to the Increment/Decrement Exp

6. Updation takes place and the flow goes to Step 3


again

7. The for loop has ended and the flow has gone
outside.
Example1

public class Test


{
public static void main(String args[])
{
for(int x = 10; x < 20; x = x + 1)
{
System.out.println("value of x : " + x );
}
}
}
class NestedFor {
public static void main(String[] args)
{
int weeks = 3;
int days = 7;
// outer loop prints weeks
for (int i = 1; i <= weeks; ++i) {
System.out.println("Week: " + i);

// inner loop prints days


for (int j = 1; j <= days; ++j) {
System.out.println(" Day: " + j);
}
}
}
}
package pack;
public class Pattern
{
public static void main(String[] args)
{
int i,j;

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.

In addition, Java provides the continue


statement. The continue statement skips all the
statements following the continue statement
and moves the control back to the loop
statement.
public class BreakTest
{
public static void main(String args[])
{
for(int count=0;count<10;count++)
{
if(count==7)
{
break;
}
System.out.println(count);
}
}
}

public class ContinueTest


{
public static void main(String args[])
{
for(int count=0;count<10;count++)
{
if(count==3)
{
continue;
}
System.out.println(count);
}
}
}
Java While Loop
The Java while loop is used to iterate a part of
the program repeatedly until the specified
Boolean condition is true. As soon as the Boolean
condition becomes false, the loop automatically
stops.

The while loop is considered as a repeating if


statement.
If the number of iteration is not fixed, it is
recommended to use the while loop.

Syntax:
while (condition){
//code to be executed
Increment / decrement statement
}
How Does a While loop execute?

1. Control falls into the while loop.

2. The flow jumps to Condition

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

4. The statements inside the body of the loop get


executed.

5. Increment/Decrement takes place.

6. Control flows back to Step 2.

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;

// Exit when x becomes greater than 4


while (x <= 10) {
// summing up x
sum = sum + x;

// Increment the value of x for next iteration


x++;
}
System.out.println("Summation: " + sum);
}
}
do-while Loop in Java
The Java do-while loop is used to iterate a part of the
program repeatedly, until the specified condition is
true. If the number of iteration is not fixed and you
must have to execute the loop at least once, it is
recommended to use a do-while loop.

Java do-while loop is called an exit control loop.


Therefore, unlike while loop and for loop, the do-while
check the condition at the end of loop body. The
Java do-while loop is executed at least once because
condition is checked after loop body.
Execution of do-While loop
1. Control falls into the do-while loop.

2. The statements inside the body of the loop get


executed.

3. Updation (Increment/Decrement) takes place.

4. The flow jumps to Condition

5. Condition is tested.
1. If Condition yields true, go to Step 6.
2. If Condition yields false, the flow goes outside the
loop

6. The flow goes back to Step 2.


Example

public class DoWhileTest


{

public static void main(String args[])


{
int x = 10;

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.

The limitation of the enhanced for loop is that


it cannot traverse the elements in reverse
order. Here, you do not have the option to skip
any element because it does not work on an
index basis. Moreover, you cannot traverse the
odd or even elements only.
Syntax: for each loop in Java

for (type var : array | Collection)


{
statements using var;
}
// Java program to illustrate
// for-each loop
class For_Each
{
public static void main(String[] arg)
{
{
int[] marks = { 125, 132, 95, 116, 110 };

int highest_marks = maximum(marks);


System.out.println("The highest score is " + highest_marks);
}
}
public static int maximum(int[] numbers)
{
int maxSoFar = numbers[0];

// for each loop


for (int num : numbers)
{
if (num > maxSoFar)
{
maxSoFar = num;
}
}
return maxSoFar;
}
Labelled Loop in Java
In Java, we can give a label to a loop.

A label is a valid variable name in Java that represents


the name of the loop to where the control of execution
should jump.

To label a loop, place the label before the loop with a


colon at the end.

The general syntax to give a label to loops is as follows:

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");
}
}

You might also like