Está en la página 1de 8

CONTINUACION CAPITULO 0

ARRAYS (VECTORES- MATRICES)

Un array es una estructura de datos que contiene una colección de datos del mismo tipo.
PROPIEDADES DE LOS ARRAYS
- Los arrays se utilizan como contenedores para almacenar datos relacionados (en vez de declarar
variables por separado para cada uno de los elementos del array).
- Todos los datos incluidos en el array son del mismo tipo. Se pueden crear arrays de tipo int o de
reales de tipo float, pero en un mismo array no se pueden mesclar datos de tipo int y de tipo float.
- El tamaño del array se establece cuando se crea el array (con el operador new, igual que cualquier
otro objeto).
- A los elementos del array se accederá a través de la posición que ocupan dentro del conjunto de
elementos del array.
TERMINOLOGIA
Los arrays unidimensionales se conocen con el nombre de vectores.
Los arrays bidimensionales se conocen con el nombre de matrices.

1. VECTOR

DECLARACION DE UN VECTOR

tipo nombre_vector[ ];

o bien

tipo[ ] nombre_vector;

donde :

tipo es el tipo de dato de los elementos del vector.

nombre_vector es el identificador de la variable.

CREACION.

Los vectores se crean con el operador new.

nombre_vector = new tipo[numero de elementos];

O bien

TipodeElemento[] NombredeArray = new TipodeElementos[tamanoArray]

Ejemplos:
// creación
int vec[ ]=new int[7];

// crear arrays inicializando con determinados valores


int v[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

1
CONTINUACION CAPITULO 0

Para acceder a los elementos de un array, utilizamos índices (para indicar la posición del elemento
dentro del array)

vector[indice]

- El índice de la primera componente de un vector es siempre 0.


- El tamaño del vector puede obtenerse utilizando la propiedad vector.length.

- Por tanto, el índice de la última componente es vector.length-1.

Ejemplo:

float vec[ ] = new float[3];

vec[0] vec[1] vec[2]

? ? ?
vec

Ejemplos:

1. Leer 5 números y mostrarlos en el mismo orden introducido.

import java.util.Scanner;
public class Vector1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t[];
t = new int[5];
for (int i=0;i<5;i++)
{
System.out.print("Introduzca un dato para la posicion "+i+": ");
t[i]=sc.nextInt();
}
System.out.println("Los datos introducidos al vector t son:");
for (int i=0;i<5;i++)
System.out.println(t[i]);
}
}

2. Programa que cuenta el número de elementos positivos, negativos y ceros de un vector de 10


elementos.

import java.util.*;
public class vector2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] numeros = new int[10];
int pos = 0, neg = 0, cero = 0; //contadores para positivos,
negativos y ceros
int i;
//Leemos los valores por teclado y los guardamos en el vector
System.out.println("Lectura de los elementos del vector: ");

2
CONTINUACION CAPITULO 0

for (i = 0; i < numeros.length; i++) {


System.out.print("numeros[" + i + "]= ");
numeros[i] = sc.nextInt();
}
//se recorre el array para contar positivos, negativos y ceros
for (i = 0; i < numeros.length; i++) {
if (numeros[i] > 0) {
pos++;
} else if (numeros[i] < 0) {
neg++;
} else {
cero++;
}
}
//mostrar resultados
System.out.println("Positivos: " + pos);
System.out.println("Negativos: " + neg);
System.out.println("Ceros: " + cero);
}
}

3. Programa que dado dos vectores definidos saca la media de ambos vectores.

public class Vectores {


static void mostrarVector(int datos[])
{
int i;
for(i=0;i<datos.length;i++)
System.out.println(datos[i]);
}

static float media(int datos[])


{
int i;
int n=datos.length;
int suma=0;

for(i=0;i<n;i++)
suma=suma+datos[i];
return suma/n;
}

public static void main(String[] args) {


int pares[]={2,4,6,8,10};
int impares[]={1,3,5,7,9};
mostrarVector(pares);
System.out.println("MEDIA="+media(pares));

mostrarVector(impares);
System.out.println("MEDIA="+media(impares));
}

3
CONTINUACION CAPITULO 0

Ejercicios en classroom.

2. MATRIZ

Una matriz, en realidad, es un vector de vectores.

Cada elemento de una matriz tiene una posición dado por la fila y columna, las mismas que
empieza en cero.

Entonces podemos ver que cada elemento de una matriz tiene una posición (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

DECLARACION DE UNA MATRIZ

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 número de elementos requerido
para arreglo.

Entonces para declarar la matriz M de los ejemplos anteriores sería:

4
CONTINUACION CAPITULO 0

En java:

tipo nombre_matriz[ ] [ ];

o bien

tipo [ ] [ ] nombre_matriz;

CREACION.

Nombre_matriz=new tipo[filas][columnas];

Ejemplo:

int [ ][ ] matriz=new int [12][30];

Uso de la matriz:

Nombre_matriz[indice1][indice2]

- En java, el índice de la primera componente de un vector es siempre 0, por lo que matriz[0][0]


sera el primer elemento de la matriz.
- El tamaño del array puede obtenerse utilizando la propiedad array.length:
matriz.length nos da el numero de filas
matriz[0].length nos da el numero de columnas
- Por tanto el ultimo elemento de la matriz es
Matriz [matriz.length-1] [matriz[0].length-1]

También se puede inicializar de la siguiente forma:

int matriz[][]={{1,2,3}, {4,5,6}};

EJEMPLO

1. Crear una matriz de tamaño 5x5 y rellenarla de la siguiente forma: la posición T[n,m]
debe contener n+m. Después se debe mostrar su contenido.

public class Matriz1 {


public static void main(String[] args) {
int t[][]; // definimos t como una tabla bidimensional
t = new int [5][5]; // creamos la tabla de 5x5
for (int i=0;i<5;i++) // utilizamos i para la primera dimensión
{
for (int j=0;j<5;j++) // utilizamos j para la segunda dimensión
{
t[i][j]=i+j;
}

5
CONTINUACION CAPITULO 0

}
System.out.println("Matriz: ");
for (int i=4;i>=0;i--)
{
System.out.println();
for (int j=0;j<5;j++)
{
System.out.print(t[i][j]+" ");
}
}
}
}

2. Programa que permite el llenado de los contenidos de la matriz y los muestra mediante métodos.

import java.util.Scanner;

public class EjemploMatriz0 {

Scanner Leer = new Scanner(System.in);

void llenarMatriz (int M [] [], int f, int c)


{
for (int i = 1 ; i <= f ; i++)
{
for (int j = 1 ; j <= c ; j++)
{
System.out.print ("Inserte pos[" + i + "][" + j + "]: ");
M [i] [j] = Leer.nextInt();
}
}
}
void mostrarMatriz (int M [] [], int f, int c)
{
for (int i = 1 ; i <= f ; i++)
{
System.out.println ();
for (int j = 1 ; j <= c ; j++)
{
System.out.print ("[" + M [i] [j] + "]");
}
}
}

public static void main (String args [])


{
Scanner Leer = new Scanner(System.in);
EjemploMatriz0 h = new EjemploMatriz0 ();
int Z [] [] = new int [20] [20];
System.out.print("Inserte el tamaño de filas de la matriz: ");
int f = Leer.nextInt();
System.out.print("Inserte el tamaño columnas de la matriz: \n");
int c = Leer.nextInt();

System.out.print("LLENANDO MATRIZ: \n");


h.llenarMatriz(Z, f, c);

6
CONTINUACION CAPITULO 0

System.out.print("LA MATRIZ Z: \n");


h.mostrarMatriz(Z, f, c);

}
}

3. Crear una matriz de n * m filas (cargar n y m por teclado) Imprimir la matriz completa y la última fila.

import java.util.Scanner;
public class EjemploMatriz2 {
private Scanner teclado;
private int[][] mat;

public void cargar() {


teclado=new Scanner(System.in);
System.out.print("Cuantas fila tiene la matriz:");
int filas=teclado.nextInt();
System.out.print("Cuantas columnas tiene la matriz:");
int columnas=teclado.nextInt();
mat=new int[filas][columnas];
for(int f=0;f<mat.length;f++) {
for(int c=0;c<mat[f].length;c++) {
System.out.print("Ingrese componente:");
mat[f][c]=teclado.nextInt();
}
}
}

public void imprimir() {


for(int f=0;f<mat.length;f++) {
for(int c=0;c<mat[f].length;c++) {
System.out.print(mat[f][c]+" ");
}
System.out.println();
}
}

public void imprimirUltimaFila() {


System.out.println("Ultima fila");
for(int c=0;c<mat[mat.length-1].length;c++) {
System.out.print(mat[mat.length-1][c]+" ");
}
}

public static void main(String[] ar) {


EjemploMatriz2 ma=new EjemploMatriz2();
ma.cargar();
ma.imprimir();
ma.imprimirUltimaFila();
}
}

4. Programa que dada una matriz intercambiar los elementos de la primera columna con la última
columna.

import java.util.Scanner;

7
CONTINUACION CAPITULO 0

public class EjemploMatriz1 {


Scanner Leer = new Scanner(System.in);
void llenar (int M [] [], int f, int c)
{
for (int i = 1 ; i <= f ; i++)
{
for (int j = 1 ; j <= c ; j++)
{
System.out.print ("Inserte pos[" + i + "][" + j + "]: ");
M [i] [j] = Leer.nextInt();
}
}
}
void mostrar (int M [] [], int f, int c)
{
for (int i = 1 ; i <= f ; i++)
{
System.out.println ();
for (int j = 1 ; j <= c ; j++)
{
System.out.print ("[" + M [i] [j] + "]");
}
}
}
void intercambiar (int M [] [], int f, int c)
{
for (int i = 1 ; i <= f ; i++)
{
int aux = M [i] [1];
M [i] [1] = M [i] [1];
M [i] [1] = aux;
}
}
public static void main (String args [])
{
Scanner Leer = new Scanner(System.in);
EjemploMatriz1 h = new EjemploMatriz1();
int M [] [] = new int [20] [20];
System.out.print ("\nInserte filas de la matriz: ");
int f = Leer.nextInt();
System.out.print ("\nInserte columnas de la matriz: ");
int c = Leer.nextInt();

System.out.print ("\nLLENANDO MATRIZ : n");


h.llenar (M, f, c);
System.out.print ("\nLA MATRIZ ORIGINAL : ");
h.mostrar (M, f, c);
System.out.print ("\n\nLA MATRICES INTERCAMBIADA : ");
h.intercambiar (M, f, c);
h.mostrar (M, f, c);
}
}

Ejercicios en classroom

También podría gustarte