Loop Statements



  • Looping means a set of instructions/functions repeatedly based on condition.
  • Java provides two ways...
  • Entry Controlled loop
    • 1.0 for loop
    • 1.1 enhanced for loop (Foreach)
    • 2. while loop
  • Exit Controlled loop
    • 3. do..while loop

1.0 for loop:

  • A for loop is entry control loop.
  • It is allows code to be executed repeatedly based on a given Boolean condition. 
  • Syntax :

for (Initialization;Condition;Increment/Decrement)
{
Statements;
}

  • Example:

for (int x = 1; x <= 4; x++)
System.out.println(x);

1.1 enhanced for loop (Foreach): 

  • Enhanced for loop provides a simpler way.
  • It is to iterate through the elements of a collection or array. 
  • It works on elements basis not index. 
  • It returns element one by one in the defined variable.


  • Syntax:

for (type element:Collection)
{
    Statements;
}

  • Example:

String names[] = {"Sarthak", "Patel", "Khadalpur"};
for (String x:names)
        {
            System.out.println(x);
        }

2. While loop: 

  • A while loop is an entry control loop.
  • It is allows code to be executed repeatedly based on a given Boolean condition. 
  • Syntax :

Initialization;
while (Condition)
{
   Statements;
   Increment/Decrement;
}

  • Example:

int x = 1;
while (x <= 4)
        {
            System.out.println(x); 
            x++;
        }

3. Do...While loop: 

  • A do..while loop is exit control loop.
  • It is allows code to be executed repeatedly based on a given Boolean condition. 
  • Syntax:

do
{
   Statements;
   Increment/Decrement;
}while (Condition);

  • Example:

int x = 1;
do
        {
            System.out.println(x); 
            x++;
        } while (x <= 4);

Thanks a lot for query or your valuable suggestions related to the topic.

Previous Post Next Post

Contact Form