Translate

For loop in Java.

For loop in Java

 
  • In for loop there are three part initialization,condition and increment/decrement.
  • Initialization part executes only once.
  • Condition part defines the condition for the execution of code block.
  • All the three part of for loop are optional.
class Easy
{
 public static void main(String[] args) 
 {
  for (int i = 1; i <5; i++) 
  {
   System.out.println(i);       
  }
 }
}
/*
### Output ###
1
2
3
4
*/
In the above example initialization part initialize 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 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
*/
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
*/

//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
*/
Next Post Previous Post
No Comment
Add Comment
comment url