The code expalins this principle –
package com.twister;
import java.util.Scanner;
class Matrix{
public static void main(String a[])
{
int r,c;
int i,j,k=0;
int matrix[][] = new int[10][10];
r = 2; c= 2;
/*Variable k is used to determine whether the for Loop
is currently scanning elements or printing them
k = 0 Loop is in scan mode
k = 1 Loop is in print mode
*/
for(j=0,i=0;i<r && j<c && k!=2;j++){
if(k==0) //Scan mode
matrix[i][j] = new Scanner(System.in).nextInt();
if(k==1) //Print Mode
System.out.print(matrix[i][j]+ " ");
if(i==r-1 && j==c-1){ //Swap from scan mode to print mode
k++;
i=0;j=-1;
}
if(j==(c-1)){
j=-1;i++;
if(k==1)
System.out.println(""); //Prints a Blank line
}
}
}
}
My personal favorite solution for this puzzle is the one by Kannan - Short, concise and gets the Job done!
Leaders board to be update with the next post!
No comments:
Post a Comment
Solution for this question?