Pattern-Double Zig Zag




Java Code:

import java.util.*;
public class Hello {

    public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int n,N,c=1;
n=s.nextInt();
int a[][]=new int[n][n];
N=n/2;
for(int i=1;i<=n;i++)
{
    if(i!=1&&i%2==0)
        c+=N-1;
    else if(i%2==1&&i!=1)
        c+=N+1;
    for(int j=1;j<=N;j++)
    {
        if(i%2==1)
        {
            a[i-1][j-1]=c++;
        }
        else
        {
            a[i-1][j-1]=c--;
        }
    }
}
c=n*N+1;
for(int i=1;i<=n;i++)
{
    if(i!=1&&i%2==1)
    c+=N+1;
    else if(i!=1&&i%2==0)
    c+=N-1;
    for(int j=N+1;j<=n;j++)
    {
        if(i%2==1)
        {
            a[i-1][j-1]=c++;
        }
        else
        {
            a[i-1][j-1]=c--;
        }
    }
}
for(int i=0;i<n;i++)
{
    for(int j=0;j<n;j++)
    {
        System.out.print(a[i][j]+" ");
    }
    System.out.println();
}
    }
}

Comments

Popular posts from this blog

Fisherman's Mantra

First & Last X Digits

N Integers – Sum S – All Combinations(Weekly Test)