Java Loop statements

Java Loop statements
Whenever we want to execute a block of statements several times then we use Loop structures.

There are four types of loop structure in Java.
1) for Loop

2) while Loop

3) do...while Loop

4) Enhanced for Loop
-------------------------
1) for Loop
It repeats a block of statements for a specified number of times.

Syntax:
for(stratvalue; endValue; increment/decrement) {
Statements
---------
--------
}

Example:
for (int i=1; i<=10; i++)
        {
            System.out.println(i);
        }
Example 2:
// print 10 to 1 Numbers using For Loop.
       
        for (int i=10; i>=1; i--)
        {
            System.out.println(i);
        }
Example 3:// print every 10th Number up to 100.
       
        for (int i=10; i<=100; i=i+10)
        {
            System.out.println(i);
        }
--------------------------------------
2) while Loop
It repeats a block of statements while condition is true.

Syntax:
Initialization
while (condition) {
statements
------
-------
increment/decrement
}

Example:// print 1 to 10 Numbers using While Loop.
       
        int i = 1;
        while (i <=10){
            System.out.println(i);
            i++;
        }
Example 2:// print 10 to 1 Numbers using While Loop.
       
        int i = 10;
        while (i >= 1){
            System.out.println(i);
            i--;
        }
Example 3:// print every 10th number up to 100 using While Loop.
       
        int i = 10;
        while (i <= 100){
            System.out.println(i);
            i= i+10;
        }
--------------------------------------

3) do ...while Loop---------------------------------------
it repeats a block of statements while condition is true and Irrespective of the condition, it executes a block of statements at least once.

Syntax:
do
{
Statements
----------
----------
Increment/Decrement
} while(Condition);
------------
Example:int i = 20;
        do {
         System.out.println("i value is : " + i);
                i++;
        } while(i <= 10);
---------------------------------------

4) Enhanced for Loop---------------------------------------
It executes all elements in an Array

Syntax:
for (declaration: expression) {
statements
----------
-----------
}

Example:String languages [] = {"C", "C++", "Java", "COBOL"};
        for (String lang: languages)
        {
            System.out.println(lang);
        }
------------------------

Also Read:


Java Variables

Java Operators 

Java Conditional Statements 

Java Arrays 

Java Methods

0 comments:

Post a Comment