Impact-Site-Verification: dbe48ff9-4514-40fe-8cc0-70131430799e

## Search This Blog

Given a number n, create an n-by-n matrix in which the integers from 1 to n^2 wind back and forth along the rows as shown in the examples below.
Examples:
Input  n = 3
Output a =    [ 1 2 3
6 5 4
7 8 9 ]
Input  n = 4
Output a =    [ 1     2     3     4
8     7     6     5
9    10    11    12
16    15    14    13 ]

MATLAB CODE:

clc

x=input('Enter the number:');
m=1;
Y=[];
for i=1:x
if(rem(i,2)==0)
for j=x:-1:1
Y(i,j)=m;
m=m+1;
end
else
for j=1:x
Y(i,j)=m;
m=m+1;
end
end
end
disp(Y)

Explanation:

OUTPUT:

JAVA CODE:

import java.util.Scanner;
class Wy
{
public static void main(String args[])
{
Scanner obj=new Scanner(System.in);
System.out.println("Enter the number:");
int n=obj.nextInt();
int k=1;
int Y[][]=new int[n][n];
for(int i=0;i<n;i++)
{
if((i%2)==0)
{
for(int j=0;j<n;j++)
{
Y[i][j]=k;
k=k+1;
}
}
else
{
for(int j=n-1;j>=0;j--)
{
Y[i][j]=k;
k=k+1;
}
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(Y[i][j]+"\t");
}
System.out.println();
}
}
}

Output: