11 Dec 2017

Write a user defined function named upper_half() which takes a square two dimensional array, with size as argument and prints the upper half of the array.


Write a user defined function named upper_half() which takes a square two dimensional array, with size as argument and prints the upper half of the array.
e.g:
2 3 1 5 0                               2 3 1 5 0
7 1 5 3 1                                  1 5 3 1
2 5 7 8 1     The output will be      7 8 1
0 1 5 0 1                                        0 1
3 4 9 1 5                                          5
import java.util.Scanner;

class Upper_Half_of_Square_Matrix {
          static void input(int matrix[][], int n) {
                   int i;
                   System.out.println("Enter data in for ");
                   for (i = 0; i < n; i++) {
                             int j = 0;
                             String str = new Scanner(System.in).nextLine();
                             Scanner scn = new Scanner(str);
                             while (scn.hasNext()) {
                                      matrix[i][j++] = Integer.parseInt(scn.next());
                             }
                   }
          }

          static void display(int matrix[][], int n) {
                   int i, j;
                   System.out.println("Your given square Matrix is ::");
                   for (i = 0; i < n; i++) {
                             for (j = 0; j < n; j++) {
                                      System.out.print(matrix[i][j] + " ");
                             }
                             System.out.println();
                   }
          }

          static void upper_half(int matrix[][], int n) {
                   int i, j;
                   System.out.println("Your Upper Half Matrix is ::");
                   for (i = 0; i < n; i++) {
                             for (j = 0; j < n; j++) {
                                      if (i <= j) {
                                                System.out.print(matrix[i][j]);
                                      } else {
                                                System.out.print(" ");
                                      }
                             }
                             System.out.println();
                   }
          }

          public static void main(String[] args) {
                   int array[][] = new int[10][10];
                   System.out.println("Enter size of square matrix :");
                   int s = new Scanner(System.in).nextInt();
                   input(array, s);
                   display(array, s);
                   upper_half(array, s);
          }
}

Output: