Matrices Java
Matrices Java
Una matriz es un array bidimensional (2 dimensiones, filas y columnas) Cmo algunos ejemplos de vectores podramos tener:
3 7 2 6 3.0 7.4 2.5 6.0
Matriz de Enteros
4 6 4 8 2 4 6 8
Matriz de Reales
a B
3 8 {
0 y i
Matriz de Caracteres
= / h .
4 6 4 8 2 4 6 8
Nombre de la Matriz
Elementos de la matriz
Cada elemento de una matriz tiene una posicin dado por la fila y columna, las mismas que empieza en cero Sea la Matriz M 0 1 2 3 Posicin columnas 0 3 7 2 6 Posicin filas 1 2
4 6 2 4 4 8 6 8
Entonces podemos ver que cada elemento de una matriz tiene una posicin (dado por la fila y columna) y un dato Por ejemplo: M[0][1] tiene el dato 7 M[3][2] error porque no existe la fila 3 M[2][0] tiene el dato 2 M[2][3] tiene el dato 8 .. Cada elemento del vector puede ser manejado como cualquier variable. Por ejemplo: int A = M[0][1] + M[1][1]; int B = 2 + M[1][2]; M[0][0] = A + B; // A = 7 + 6 = 13 // B = 2 + 4 = 6 // M[0][0] = 13 + 6 = 19
Declaracin de Matrices en JAVA Los arreglos ocupan espacio en la memoria. El programador especifica el tipo de los elementos y usa el operador new para asignar espacio de almacenamiento al nmero de elementos requerido para arreglo. Entonces para declarar la matriz M de los ejemplos anteriores sera:
En JAVA una vez creado un vector con datos numricos los datos del vector por defecto se inicializan en cero
0 0 0 0
M=
0 0 0 0 0 0 0 0
1. Realizar un programa para insertar datos por teclado en una matriz de 3 x 3 y posteriormente visualizar los datos de la matriz import java.io.*; class matriz { public static void main(String args[])throws IOException { BufferedReader EN=new BufferedReader(new InputStreamReader(System.in)); int M[][]=new int[3][3]; for(int i=0;i<3;i++) for(int j=0;j<3;j++) M[i][j]=Integer.parseInt(EN.readLine()); for(int i=0;i<3;i++) { for(int j=0;j<3;j++) System.out.print(M[i][j]+" "); System.out.println(); } } } 2. Realizar un programa para insertar datos por teclado en una matriz de M x N (M y N introducidos por teclado) y posteriormente visualizar los datos de la matriz
import java.io.*; class matriz { public static void main(String args[])throws IOException { BufferedReader EN=new BufferedReader(new InputStreamReader(System.in)); int mat[][]=new int[10][10]; int M,N; System.out.println("inserte la cantidad de filas"); M=Integer.parseInt(EN.readLine()); System.out.println("inserte la cantidad de columnas"); N=Integer.parseInt(EN.readLine());
Declaracin de la matriz M de 3 x 3
M y N por teclado
System.out.println("inserte los datos"); for(int i=0;i<M;i++) for(int j=0;j<N;j++) mat[i][j]=Integer.parseInt(EN.readLine()); for(int i=0;i<M;i++) { for(int j=0;j<N;j++) System.out.print(mat[i][j]+" "); System.out.println(); } } }