Thursday, September 17, 2015

Interesting Pattern with single for loop!

Minimum loop required to print below Pattern (can be n*n).

4 4 4 4 4 4 4 
4 3 3 3 3 3 4 
4 3 2 2 2 3 4 
4 3 2 1 2 3 4 
4 3 2 2 2 3 4 
4 3 3 3 3 3 4 
4 4 4 4 4 4 4 

import java.lang.Math;
public class NxNPattern
{
public static void main(String[] args)
{
for (int i = 0, j = 0; i < 49; i++) {
if (i % 7 == 0) {
if (j > 0) System.out.println();
j++;
}
int x = Math.abs(i % 7 - 3);
int y = Math.abs(j - 4);
if (x < y) System.out.print(y + 1);
else System.out.print(x + 1);
}
}
}
view raw NxNPattern.java hosted with ❤ by GitHub

No comments:

Post a Comment