For loop in Java programming Hands on Coding

For loop in Java;

In this section let's see about for loop in java.


Syntax: 

  • For loop contains three parts initialization, condition and increment/decrement.
  • Initialization part executes only once.
  • Condition part will define the condition for the execution of code block.
  • All the three parts of for loop are optional.


Example 1:

 class Easy   
 {   
  public static void main(String[] args)   
  {   
    for (int i = 1; i <5; i++)   
    {   
     System.out.println(i);   
    }   
  }   
 }   
 / ### Output ###   
 1 
 2 
 3 
 4 

Explaination:

In the above example initialization part initializes the variable i with 1, condition is i less than 5 and at the increment place there is an increment by 1 ,so the output will be 1 to 4.



Example 2:

Example 1 can also be written like the code below.

 class Easy   
 {   
  public static void main(String[] args)   
  {   
    int i = 1;   
   for (; i <5; )   
   {   
     System.out.println(i);   
     i++;   
   }   
  }   
 }   
 / ### Output ### 1 2 3 4 /   



Example 3:

 class Easy   
 {   
  public static void main(String[] args)   
  {   
   //all parts of for loop are optional   
   for(;;)   
   System.out.println("Hello");   
  }   
 }   
 ### Output ###   
 Hello   
 Hello   
 Hello   
 Hello   
 -----   
 -----   
 Infinite time Hello   



Example 4: Find factorial of any number

 //factorial of 5=1x2x3x4x5   
 //factorial of 6=1x2x3x4x5x6   
 //factorial of N=1x2x3x....xN   
 import java.util.Scanner;   
 class Easy   
 {   
  public static void main(String[] args)   
  {   
   Scanner in=new Scanner(System.in);   
   int no,f=1;   
   System.out.println("Enter any number");   
   no=in.nextInt();   
   for (int i = 1; i <=no; i++)   
    {   
     f=f*i;   
    }   
    System.out.println("The factorial of "+no+" is "+f);   
  }   
 }   
 ### Output ###   
 Enter any number 6   
 The factorial of 6 is 720   

For Videos Join Our Youtube Channel: Join Now

Thank you!