For loop in Java

 

Java for loop

In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check the condition, and increment/decrement in a single line of code. We use the for loop only when we exactly know the number of times, we want to execute the block of code.

  1. for(initialization, condition, increment/decrement) {    
  2. //block of statements    
  3. }    

The flow chart for the for-loop is given below.

Control Flow in Java

Consider the following example to understand the proper functioning of the for loop in java.


//print "I love my India" 10 times

  1. public class ForLoop1 {

    public static void main(String []args){

    for(int i=1;i<=10;i++){

    System.out.println("I love my India");

    }

    }

    }


Output:

I love my India
I love my India
I love my India
I love my India
I love my India
I love my India
I love my India
I love my India
I love my India
I love my India


//print 1 to 10

  1. public class ForLoop2 {

    public static void main(String[] args) {

    for(int i=1; i<=10;i++){

    System.out.println(i);

    }

    }

    }

Output:

1
2
3
4
5
6
7
8
9
10


//print all even number from 1 to 10

  1. public class ForLoop3{

    public static void main(String[] args) {

    for(int i=1;i<=10;i++){

    if(i%2==0){

    System.out.println(i);

    }

    }

    }

    }


Output:

2
4
6
8
10


//print all even numbers from 1 to 100 which are divisible by 5

  1. public class ForLoop4{

    public static void main(String[] args) {

    for(int i=1;i<=100;i++){

    if(i%2==0){

    if(i%5==0){

    System.out.println(i);

    }

    }

    }

    }

    }

Output:

10
20
30
40
50
60
70
80
90
100

Comments

Popular Topics

What is JSP. How to create one JSP application in Eclipse

How to develop a RESTful webservice in java ?

Data Types in PL/SQL

What is JDBC ?

What is Hibernate in java ?

If you have any query or suggestions, Please feel free to write us

Name

Email *

Message *