Untitled

 avatar
unknown
plain_text
2 months ago
1.8 kB
2
Indexable
import java.util.Scanner;

public class matrices2 {
    public static void search(int matrix[][], int key) {
        boolean found = false; // Flag to check if the key is found
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                if (matrix[i][j] == key) {
                    System.out.println("Key " + key + " found at index: (" + i + ", " + j + ")");
                    found = true; // Set the flag to true if the key is found
                }
            }
        }
        if (!found) {
            System.out.println("Key " + key + " not found in the matrix.");
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        // Input for matrix size
        System.out.print("Enter the number of rows: ");
        int n = sc.nextInt();
        System.out.print("Enter the number of columns: ");
        int m = sc.nextInt();

        int matrix[][] = new int[n][m];

        // Input for matrix elements
        System.out.println("Enter the elements of the matrix: ");
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                matrix[i][j] = sc.nextInt();
            }
        }

        // Output the matrix
        System.out.println("The matrix is: ");
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }

        // Input for the key to search
        System.out.print("Enter the key to search: ");
        int key = sc.nextInt();

        // Search for the key
        search(matrix, key);

        sc.close(); // Close the scanner
    }
}
Leave a Comment