Untitled
unknown
plain_text
a year ago
1.7 kB
6
Indexable
import java.util.Scanner;
public class matrices2 {
public static boolean search(int matrix[][], int key) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (matrix[i][j] == key) {
return true; // Key found
}
}
}
return false; // Key not found
}
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
if (search(matrix, key)) {
System.out.println("Key " + key + " found in the matrix.");
} else {
System.out.println("Key " + key + " not found in the matrix.");
}
sc.close(); // Close the scanner
}
}Editor is loading...
Leave a Comment