Popular Post

Posted by : Unknown martes, 17 de junio de 2014

Crear y cargar una matriz de 4 filas por 4 columnas. Imprimir la diagonal principal.
              x    -    -    -
              -    x    -    -
              -    -    x    -
              -    -    -    x

Programa:

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

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

        public void Cargar() 
        {
            mat=new int[4,4];
            for(int f = 0; f < 4; f++) 
            {
                for(int c = 0; c<4; c++) 
                {
                    Console.Write("Ingrese componente:");
                    string linea;
                    linea = Console.ReadLine();
                    mat[f, c] = int.Parse(linea);
                }
            }
        }

        public void ImprimirDiagonalPrincipal() 
        {
            for(int k = 0; k < 4; k++) 
            {
                Console.Write(mat[k,k]+" ");
            }
            Console.ReadKey();
        }

        static void Main(string[] args)
        {
            Matriz2 ma = new Matriz2();
            ma.Cargar();
            ma.ImprimirDiagonalPrincipal();
        }
    }
}
La definición, creación y carga de la matriz no varían con el ejemplo anterior.
Para imprimir la diagonal principal de la matriz lo más conveniente es utilizar un for que se repita 4 veces y disponer como subíndice dicho contador (los elementos de la diagonal principal coinciden los valores de la fila y columna):
            for(int k = 0; k < 4; k++) 
            {
                Console.Write(mat[k,k]+" ");
            }

Leave a Reply

Subscribe to Posts | Subscribe to Comments

- Copyright © Programación #5 - Date A Live - Powered by Blogger - Designed by Johanes Djogan -