java-easyfixtechnology.com

For loop in java with examples

Loops are used to execute a set of statements until a particular condition is satisfied. Java programming language has three types of loops. There are for loop, while loop, and do-while loop. In this tutorial, We will discuss how to use for loop in java.

Syntax:

for(initialisation; condition ; increment) {
   statement(s);
}

Initialisation – execute only one time.

condition – for loop is evaluated on each iteration, When the condition is true then the statements inside for loop body gets executed.

Increment – for loop executes that updates the loop counter.

Flowchart

for loop flowchart

Example 1: Write java code for print odd numbers between 10 and 20?

public class Solution {
    public static void main(String args[]){
         for(int i=10; i<20; i++) {
             if (i%2==1) {
                 System.out.println(i);
             }
         }
    }
}

Output:

11
13
15
17
19

Example 2: Write to java code for print array element?

public class Solution {
    public static void main(String args[]){
         int Array[] = {12, 25, 40, 87}
         for(int i=0; i<arr.length; i++) {
             System.out.println(Array[i]);
         }
    }
}

Output:

12
25
40
87

Nested for loop

Java programming allows using one for loop inside of another for a loop.

Example:

public class Solution {  
    public static void main(String[] args) {
       for(int i=1; i<=5; i++) {
           for(int j=1;j<=i;j++) {
               System.out.print("*");
           }
        System.out.println();
       }
   }
}  

Output:

*
**
***
****
*****

Java is a popular programming language and widely-used programming language for many years. You can learn java programming with examples by following our Java articles sequentially.

 529 total views,  3 views today

1 thought on “For loop in java with examples”

Leave a Comment

Your email address will not be published. Required fields are marked *

wpChatIcon