Solved ProgramsISCClass 12Computer Science

Saddle Point Program in Java (ISC)

Write a program in Java to input the size of a square matrix from the user. Then allow the user to fill the matrix with integers. Now do the following:

Updated
Solved Programs

Saddle point program

Write a program in Java to input the size of a square matrix from the user. Then allow the user to fill the matrix with integers. Now do the following:

  1. Display the original matrix.
  2. Display the saddle point of the matrix if one exists, otherwise display “No saddle point”.

A saddle point of a matrix is the element in the matrix which is the smallest in its row, and the largest in its column.

Example:
INPUT:
N = 3

1 2 3

4 5 6

7 8 9

OUTPUT:

Original Matrix:

1 2 3

4 5 6

7 8 9

Saddle point = 7.

import java.io.*;

class SaddlePoint
{
    public static void main(String[] args) throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter the order of the matrix : ");
        int n = Integer.parseInt(br.readLine().trim());
        int A[][] = new int[n][n];

        System.out.println("Enter the elements of the matrix");
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                System.out.print("Enter element at [" + i + "][" + j + "] : ");
                A[i][j] = Integer.parseInt(br.readLine().trim());
            }
        }

        /* Print the original matrix */
        System.out.println("Original Matrix:");
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                System.out.print(A[i][j] + "\t");
            }
            System.out.println();
        }

        boolean found = false;
        for (int i = 0; i < n; i++)
        {
            /* Find the smallest element of row i and remember its column */
            int min = A[i][0];
            int col = 0;
            for (int j = 1; j < n; j++)
            {
                if (A[i][j] < min)
                {
                    min = A[i][j];
                    col = j;
                }
            }

            /* Find the largest element of that column */
            int max = A[0][col];
            for (int k = 1; k < n; k++)
            {
                if (A[k][col] > max)
                {
                    max = A[k][col];
                }
            }

            /* Smallest in its row and largest in its column: a saddle point */
            if (min == max)
            {
                System.out.println("Saddle point = " + min);
                found = true;
            }
        }

        if (!found)
        {
            System.out.println("No saddle point");
        }
    }
}