Monday, 5 January 2015

Java Nested For Loops

If you code a for loop within another for loop, this is called a nested for loop. You can see an example in prog67 below:

Java > cat prog67.java
public class prog67
{
public static void main (String args[])
  {
  for (int a=1;a<=4;a++)
    {
    for (int b=1;b<=4;b++)
      {
      System.out.println(a + "x" + b + "=" + a*b);
      }
    }
  }
}
Java > javac prog67.java
Java > java prog67
1x1=1
1x2=2
1x3=3
1x4=4
2x1=2
2x2=4
2x3=6
2x4=8
3x1=3
3x2=6
3x3=9
3x4=12
4x1=4
4x2=8
4x3=12
4x4=16
Java >