LOOPS: (iteration – Repeated execution)

Looping in programming languages is a feature which facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true.

TYPES OF LOOPING STATEMENTS:

For loop:

A for loop in Java is a repetition control structure which allows us to write a loop that is executed a specific number of times.

The for loop is also called an Entry Controlled loop because the test expression is tested before entering the loop body.

Loop wil execute until condition is true, when condition is false loop will be stopped.

SYNTAX:

for(initialization; condition ; increment/decrement)
{

//body of the loop


}

EXAMPLE:1

//INCREMENT
for(int i=1; i<=10; i=i+1)
{
println(i);
}

EXAMPLE:2


//DECREMENT
for(int j=10; j>=1 ; j=j-1)
{
println(j);
}

Double for loop:

For every increment of outer loop, inner loop will go for full execution.

Inner for loop is independent on outer for loop:

for(int i=1;i<=3;i=i+1)
{
for(int j=1;j<=3;j=j+1)
{
println(i+ ” ” +j);
}
}

Inner for loop is dependent on outer for loop:

for(int a=1;a<=3;a=a+1)
{
for(int b=1;b<=a;b=b+1)
{
println(a+ ” ” +b);
}
}

WHILE LOOP:

Java while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition

While loop in Java comes into use when we need to repeatedly execute a block of statements.

The while loop is considered as a repeating if statement.

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

SYNTAX:

while(condition)
{
//body of the loop
}

While loop execution: 

  1. Control falls into the while loop.
  2. The flow jumps to Condition
  3. Condition is tested.
    • If Condition yields true, the flow goes into the Body.
    • If Condition yields false, the flow goes outside the loop.
  4. The statements inside the body of the loop get executed.
  5. Updation takes place.
  6. Control flows back to Step 2.
  7. The while loop has ended and the flow has gone outside.

for and while loop looks alike:

int i=1;
while(i<=10)
{
println(i);
i=i+1;
}

Leave a comment

Design a site like this with WordPress.com
Get started