Java for loop

Hi!! coders…

First of all, let’s  know what is the loop


In programing language loop are used to execute a block of code repeatedly until a certain condition is met

suppose you want to print your name 100 times by using the print statement  

so it is very  difficult to write print statement 100 time 

so instant of this we use the loop in this we execute any statement Any number of times 

There are three types of the loop:

  1. simple for loop
  2. for each  or enhanced for loop
  3. labeled for loop  

1. Simple for loop 

Let’s see the diagram :

simple for loop in java

Syntex of for Loop:-


    //statement or code to be executed 


How Loop Work:-

As you can see in syntex it takes three parameter

Initialization: It is the initial condition which is executed once when the loop starts. Here, we can initialize the variable, or we can use an already initialized variable. It is an optional condition.

Condition: It is the second condition that is executed each time to test the condition of the loop. It continues execution until the condition is false. It must return boolean value either true or false. It is an optional condition.

Statement: The statement of the loop is executed each time until the second condition is false.

Increment/Decrement: It increments or decrements the variable value. It is an optional condition.

Example of for loop:-

// Program to print a sentence 10 times
class Loop {
   public static void main(String[] args) {
      for (int i = 1; i <= 10; ++i) {
         System.out.println("Codeelife " + i);
codeelife 1
codeelife 2
codeelife 3
codeelife 4
codeelife 5
codeelife 6
codeelife 7
codeelife 8
codeelife 9
codeelife 10

Nested For Loop:-

If we have a for loop inside another for loop, it is known as nested for loop. The inner loop executes completely whenever the outer loop executes.


public class PyramidExample {  
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();//new line  
* *
* * *
* * * *
* * * * * 


Important Link