22 - Matrices (cantidad de filas y columnas)


Como hemos visto para definir y crear la matriz utilizamos la siguiente sintaxis:

int[,] mat;

Creación:

mat=new int[3,4];

Como las matrices son objetos en C# disponemos de un método llamado GetLength que le pasamos como parámetro la dimension y nos retorna el valor de dicha dimensión.
Si queremos saber la cantidad de filas que tiene la matriz debemos llamar al método GetLength con el valor cero:

Console.WriteLine("Cantidad de filas de la matriz:" + mat.GetLength(0));

Si queremos saber la cantidad de columnas luego:

Console.WriteLine("Cantidad de columnas de la matriz:" + mat.GetLength(1));

La primer dimensión son la cantidad de filas y la segunda dimensión son la cantidad de columnas de la matriz.

Problema 1:

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

Programa:

Ver video

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Matriz5
{
    class Matriz5
    {
        private int[,] mat;

        public void Cargar() 
        {
            Console.Write("Cuantas fila tiene la matriz:");
            string linea;
            linea=Console.ReadLine();
            int filas=int.Parse(linea);
            Console.Write("Cuantas columnas tiene la matriz:");
            linea=Console.ReadLine();
            int columnas=int.Parse(linea);
            mat=new int[filas,columnas];
            for(int f = 0; f < mat.GetLength(0); f++) 
            {
                for (int c = 0; c < mat.GetLength(1); c++)
                {
                    Console.Write("Ingrese componente:");
                    linea = Console.ReadLine();
                    mat[f,c] = int.Parse(linea);
                }
            }
        }

        public void Imprimir() 
        {
            for(int f = 0; f < mat.GetLength(0); f++)
            {
                for(int c = 0; c < mat.GetLength(1); c++)
                {
                    Console.Write(mat[f,c]+" ");
                }
                Console.WriteLine();
            }
        }

        public void ImprimirUltimaFila() 
        {
    	    Console.WriteLine("Ultima fila");
            for(int c = 0; c < mat.GetLength(1); c++)
            {
                 Console.Write(mat[mat.GetLength(0)-1,c]+" ");
            }
        }

        static void Main(string[] args)
        {
            Matriz5 ma = new Matriz5();
            ma.Cargar();
            ma.Imprimir();
            ma.ImprimirUltimaFila();
            Console.ReadKey();
        }
    }
}

En este ejemplo cada vez que se ejecute el programa el tamaño de la matriz lo define el usuario, para ello ingresamos por teclado dos enteros y seguidamente procedemos a crear la matriz con dichos valores:

            Console.Write("Cuantas fila tiene la matriz:");
            string linea;
            linea=Console.ReadLine();
            int filas=int.Parse(linea);
            Console.Write("Cuantas columnas tiene la matriz:");
            linea=Console.ReadLine();
            int columnas=int.Parse(linea);
            mat=new int[filas,columnas];

Ahora las estructuras repetitivas las acotamos preguntando a la misma matriz la cantidad de filas y la cantidad de columnas:

            for(int f = 0; f < mat.GetLength(0); f++) 
            {
                for (int c = 0; c < mat.GetLength(1); c++)
                {
                    Console.Write("Ingrese componente:");
                    linea = Console.ReadLine();
                    mat[f,c] = int.Parse(linea);
                }
            }

El algoritmo de impresión es idéntico al visto anteriormente con la modificación de las condiciones de los for:

            for(int f = 0; f < mat.GetLength(0); f++)
            {
                for(int c = 0; c < mat.GetLength(1); c++)
                {
                    Console.Write(mat[f,c]+" ");
                }
                Console.WriteLine();
            }

Para imprimir la última fila debemos disponer un valor fijo en el subíndice de la fila (en este caso no podemos disponer un número fijo sino preguntarle a la misma matriz la cantidad de filas y restarle uno ya que las filas comienzan a numerarse a partir de cero: mat[mat.GetLength(0)-1,c]

También la condición del for debemos preguntar a la matriz la cantidad de columnas mat.GetLength(1):

    	    Console.WriteLine("Ultima fila");
            for(int c = 0; c < mat.GetLength(1); c++)
            {
                 Console.Write(mat[mat.GetLength(0)-1,c]+" ");
            }

Problema 2:

Crear una matriz de n * m filas (cargar n y m por teclado) Imprimir el mayor elemento y la fila y columna donde se almacena.

Programa:

Ver video

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Matriz6
{
    class Matriz6
    {
        private int[,] mat;

        public void Cargar() 
        {
            Console.Write("Cuantas fila tiene la matriz:");
            string linea;
            linea=Console.ReadLine();
            int filas=int.Parse(linea);
            Console.Write("Cuantas columnas tiene la matriz:");
            linea=Console.ReadLine();
            int columnas=int.Parse(linea);
            mat=new int[filas,columnas];
            for(int f = 0; f < mat.GetLength(0); f++)
            {
                for(int c = 0; c <mat.GetLength(1); c++)
                {
                    Console.Write("Ingrese componente:");
                    linea = Console.ReadLine();
                    mat[f,c]=int.Parse(linea);
                }
            }
        }

        public void ImprimirMayor() 
        {
    	    int mayor=mat[0,0];
    	    int filamay=0;
    	    int columnamay=0;
            for(int f = 0; f < mat.GetLength(0); f++)
            {
                for(int c = 0; c < mat.GetLength(1); c++) 
                {
                    if (mat[f,c] > mayor) 
                    {
                        mayor=mat[f,c];
                        filamay=f;
                        columnamay=c;
                    }
                }
            }
            Console.WriteLine("El elemento mayor es:"+mayor);
            Console.WriteLine("Se encuentra en la fila:"+filamay+ " y en la columna: "+columnamay);
            Console.ReadLine();
        }

        static void Main(string[] args)
        {
            Matriz6 ma = new Matriz6();
            ma.Cargar();
            ma.ImprimirMayor();
        }
    }
}

Para obtener el mayor elemento de la matriz y la fila y columna donde se ubica debemos inicializar una variable mayor con el elemento de la fila cero y columna cero (esto lo hacemos suponiendo que en dicha posición se almacena el mayor):

    	    int mayor=mat[0,0];
    	    int filamay=0;
    	    int columnamay=0;

Luego mediante dos for recorremos todos los elementos de la matriz y cada vez que encontramos un elemento mayor al actual procedemos a actualizar la variable mayor y la posición donde se almacena:

            for(int f = 0; f < mat.GetLength(0); f++)
            {
                for(int c = 0; c < mat.GetLength(1); c++) 
                {
                    if (mat[f,c] > mayor) 
                    {
                        mayor=mat[f,c];
                        filamay=f;
                        columnamay=c;
                    }
                }
            }

Problemas propuestos

  1. Crear una matriz de n * m filas (cargar n y m por teclado) Intercambiar la primer fila con la segunda. Imprimir luego la matriz.

    Ver video

  2. Crear una matriz de n * m filas (cargar n y m por teclado) Imprimir los cuatro valores que se encuentran en los vértices de la misma (mat[0][0] etc.)

    Ver video

Solución
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Matriz7
{
    class Matriz7
    {
        private int[,] mat;

        public void Cargar() 
        {
            Console.Write("Cuantas fila tiene la matriz:");
            string linea;
            linea=Console.ReadLine();
            int filas=int.Parse(linea);
            Console.Write("Cuantas columnas tiene la matriz:");
            linea=Console.ReadLine();
            int columnas=int.Parse(linea);
            mat=new int[filas,columnas];
            for(int f = 0; f < mat.GetLength(0); f++)
            {
                for(int c = 0;c < mat.GetLength(1); c++)
                {
                    Console.Write("Ingrese componente:");
                    linea = Console.ReadLine();
                    mat[f,c]=int.Parse(linea);
                }
            }
        }

        public void Intercambiar()
        {
            for (int c = 0; c < mat.GetLength(1); c++)
            {
                int aux = mat[0,c];
                mat[0,c] = mat[1,c];
                mat[1,c] = aux;
            }
        }

        public void Imprimir() 
        {
            for(int f = 0; f < mat.GetLength(0); f++)
            {
                for(int c = 0; c < mat.GetLength(1); c++)
                {
                    Console.Write(mat[f,c]+" ");
                }
                Console.WriteLine();
            }
            Console.ReadKey();
        }
   
        static void Main(string[] args)
        {
            Matriz7 ma = new Matriz7();
            ma.Cargar();
            ma.Intercambiar();
            ma.Imprimir();
        }
    }
}




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Matriz8
{
    class Matriz8
    {
        private int[,] mat;

        public void Cargar() 
        {
            Console.Write("Cuantas fila tiene la matriz:");
            string linea;
            linea=Console.ReadLine();
            int filas=int.Parse(linea);
            Console.Write("Cuantas columnas tiene la matriz:");
            linea=Console.ReadLine();
            int columnas=int.Parse(linea);
            mat=new int[filas,columnas];
            for(int f = 0; f < mat.GetLength(0); f++)
            {
                for(int c = 0; c < mat.GetLength(1); c++)
                {
                    Console.Write("Ingrese componente:");
                    linea = Console.ReadLine();
                    mat[f,c]=int.Parse(linea);
                }
            }
        }

        public void ImprimirVertices() 
        {
    	    Console.WriteLine("Vértice superior izquierdo:");
            Console.WriteLine(mat[0,0]);
    	    Console.WriteLine("Vértice superior derecho:");        
            Console.WriteLine(mat[0,mat.GetLength(1)-1]);
    	    Console.WriteLine("Vértice inferior izquierdo:");        
            Console.WriteLine(mat[mat.GetLength(0)-1,0]);
    	    Console.WriteLine("Vértice inferior derecho:");        
            Console.WriteLine(mat[mat.GetLength(0)-1,mat.GetLength(1)-1]);
            Console.ReadKey();
        }

        static void Main(string[] args)
        {
            Matriz8 ma = new Matriz8();
            ma.Cargar();
            ma.ImprimirVertices();
        }
    }
}

Retornar