Advertisement
plamen27

Task1c_PrintMatrix

Jan 30th, 2017
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. package fourthlec;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class Task1c_PrintMatrix {
  6. public static void main(String[] args) {
  7. Scanner sc = new Scanner(System.in);
  8. int n = sc.nextInt();
  9.  
  10. int[][] matrix = new int[n][n];
  11. int number = 1;
  12.  
  13. int i = 1;
  14. int j = 1;
  15. for (int element = 1; element <= n * n; element++) {
  16. matrix[i - 1][j - 1] = element;
  17. if ((i + j) % 2 == 0) {
  18. // Even stripes
  19. if (j < n)
  20. j++;
  21. else
  22. i+= 2;
  23. if (i > 1)
  24. i--;
  25. }
  26. else {
  27. // Odd stripes
  28. if (i < n)
  29. i++;
  30. else
  31. j+= 2;
  32. if (j > 1)
  33. j--;
  34. }
  35. }
  36.  
  37. // Print matrix:
  38. for (int row = 0; row < matrix.length; row++) {
  39. for (int col = 0; col < matrix.length; col++) {
  40. System.out.print(matrix[row][col] + " ");
  41. }
  42. System.out.println();
  43. }
  44. }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement