Java For Loop and Types of For loops and For-each loop with the Examples

Java For Loop:

The for statement is the most commonly used looping statement.  The statement includes initialization an expression that specifies an initial value for an index, and the condition expression determines whether the loop is continued or not and the last iteration expression allows the index to be modified at the end of each pass.

Types of for loops: There are two types of for loops. They are:

  1. for() loop.
  2. for-each loop (enhanced for loop).

Syntax of for() loop:

for(initialization; condition; iteration)
{
//codes to be Executed//
}
Java For loop logic diagram

Java For Loop Example:

Java For Example programs:
class Forexample
{
 public static void main(String[] args)
 {         
  int i;
  for(i = 1; i<=10; i++)
  {
   System.out.println("value of i = " +i);
  }
  System.out.println("Example of For Loop");
 }
}
Java For output:
value of i = 1
value of i = 2
value of i = 3
value of i = 4
value of i = 5
value of i = 6
value of i = 7
value of i = 8
value of i = 9
value of i = 10
Example of For Loop

Explanation of the above program:

  • Variable of type int (integer) is declared.
  •  Now in for loop first it is initialized as 1.
  • Now the condition is checked 1 is less than 10. So the value is printed.
  • The loop continues until the value of “i” becomes “11” the condition (11<=10) is false so the control jumps out of for loop.

In the above, we explained using Increment operator. Java For Loop using Decrement operator we use for loop:

Java For loop programs:
class Forexample1
{
 public static void main(String[] args)
 {
  int i;
  for(i = 4; i>=1; i--)
  {
   System.out.println("value of i = " +i);
  }
 }
}

Java For loop output:
value of i = 4
value of i = 3
value of i = 2
value of i = 1
For-each loop(enhanced for loop): It is a specially designed loop to iterate the elements of arrays and collections.

Syntax:

for(Type variable : array)
{
 //code to be executed//

}

Java For - Each loop programs:
class ForEachExample
{
 public static void main(String[] args)
 {
  int i[] = {1,2,3,4,5};
  for(int j : i)
  {
   System.out.println("j = " +j);
  }                    
 }
Java For - Each loop output:
j = 1
j = 2
j = 3
j = 4
j = 5
Nested for loops: Nested for loops allow loops to be nested. That is one for loop present inside another for a loop.

Nested for loop Program in Java:

Java Nested For loop programs:
class NesExample
{
 public static void main(String[] args)
 {
  int i,j;
  for(i = 0; i < 5; i++)
  {
   for(j = i; j < 5; j++)
   {
    System.out.print("*");
   }
   System.out.println();
  }
 }
}
Java Nested loop output:
*****
****
***
**
*
Read Also:
Share:

Our Services

Search This Blog

  • ()
Powered by Blogger.

C Data Types and Types of data types in C

Data types specify the type of data that a variable can store. All C compilers support Five fundamental data types, they are an integer(int...