Advertisement
IrinaIgnatova

Print diagonals of square matrix

Oct 7th, 2019
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.09 KB | None | 0 0
  1. package com.company;
  2.  
  3.  
  4. import java.io.IOException;
  5.  
  6.  
  7. import java.util.*;
  8.  
  9. public class Main {
  10.  
  11.  
  12.     public static void main(String[] args) {
  13.         Scanner scanner = new Scanner(System.in);
  14.  
  15.         int size = Integer.parseInt(scanner.nextLine());
  16.         int[][] matrix = new int[size][];
  17.  
  18.         for (int i = 0; i < size; i++) {
  19.             matrix[i] = Arrays.stream(scanner.nextLine().split(" "))
  20.                     .mapToInt(Integer::parseInt)
  21.                     .toArray();
  22.         }
  23.         int row = 0;
  24.         int col = 0;
  25.  
  26.         while (row < size && col < size) {
  27.             int element = matrix[row][col];
  28.             System.out.print(element + " ");// това е за първия диагонал
  29.             row++;
  30.             col++;
  31.  
  32.         }
  33.         System.out.println();
  34.         //за втория диагонал:
  35.         row = size - 1;
  36.         col = 0;
  37.         while (row >= 0 && col < size) {
  38.             int element = matrix[row][col];
  39.             System.out.print(element + " ");
  40.             row--;
  41.             col++;
  42.         }
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement