Java Program for Odd and Even Number Pattern.





package demo;
public class OddEvenPattern
{
 public static void main(String[] args) 
 {
  for (int r = 1, n = 1; r <= 5; r++, n = n + 2) 
  {
   if (r % 2 == 0) {
    for (int c = 1, p = 2; c <= n; c++, p = p + 2) 
    {
     System.out.print(" " + p);
    }
   } 
   else {
    for (int c = 1, p = 1; c <= n; c++, p = p + 2) 
    {
     System.out.print(" " + p);
    }
   }
   System.out.println();
  }
 }
}

Output:

1
 2 4 6
 1 3 5 7 9
 2 4 6 8 10 12 14
 1 3 5 7 9 11 13 15 17

BUILD SUCCESSFUL (total time: 0 seconds)


No comments:

Post a Comment