Danny Muñoz
En orientación a objetos la herencia es el mecanismo fundamental para implementar la reutilización y extensibilidad del software. A través de ella los diseñadores pueden construir nuevas clases partiendo de una jerarquía de clases ya existente (comprobadas y verificadas) evitando con ello el rediseño, la modificación y verificación de la parte ya implementada. La herencia facilita la creación de objetos a partir de otros ya existentes, obteniendo características (métodos y atributos) similares a los ya existentes.
Es la relación entre una clase general y otra clase más especifica. Por ejemplo: Si declaramos una clase párrafo derivada de una clase texto, todos los métodos y variables asociadas con la clase texto, son automáticamente heredados por la subclase párrafo.
La herencia es uno de los mecanismos de la programación orientada a objetos, por medio del cual una clase se deriva de otra, llamada entonces clase base o clase padre,(a veces se le denomina superclase pero no es muy comun), de manera que extiende su funcionalidad. Una de sus funciones más importantes es la de proveer Polimorfismo y late binding.
El siguiente codigo es un ejemplo de herencia en java.
CLASE PRINCIPAL

public class Principal {

   
    public static void main(String[] args)
    {
        System.out.println("Creando Objeto Empleado....!");
        //String Cargo, String Departamento,long Cedula, String Nombres, int Edad
        Empleado Juan = new Empleado("Director", "Sistemas","12034576891","Mariuxi Lopez",35);
        Juan.DatosInformativos();
        System.out.println(Juan.CalcularSueldo(60,18));
       
        System.out.println("Creando Objeto Estudiante....!");
        //String Colegio, String Semestre, String Cedula, StriSng Nombres, int Edad
        Estudiante Pedro = new Estudiante("Monterrey","Octavo","1207895431","Carlos Torres", 15);
        Pedro.setEspecialidad("Telecomunicacion");
        Pedro.DatosInformativos();
    }
}

CLASE PERSONA


public class Persona
{
    private String Cedula;
    private String Nombres;
    private int Edad;

    public Persona(String Cedula, String Nombres, int Edad) {
        this.Cedula = Cedula;
        this.Nombres = Nombres;
        this.Edad = Edad;
    }
   
    public void DatosInformativos()
    {
      System.out.println("Cedula Identidad: " + this.Cedula);
      System.out.println("Nombres: " + this.Nombres);
      System.out.println("Edad: " + this.Edad);
    }
   
}

CLASE ESTUDIANTE

public class Estudiante extends Persona
{
    private String Colegio;
    private String Semestre;
    private String Especialidad;

    public void setEspecialidad(String Especialidad) {
        this.Especialidad = Especialidad;
    }

    public Estudiante(String Colegio, String Semestre, String Cedula, String Nombres, int Edad) {
        super(Cedula, Nombres, Edad);
        this.Colegio = Colegio;
        this.Semestre = Semestre;
    }

    @Override
    public void DatosInformativos() {
        super.DatosInformativos();
        System.out.println("Colegio: " + this.Colegio);
        System.out.println("Semestre: " + this.Semestre);
        System.out.println("Especialidad: " + this.Especialidad);
    }
   
   
}

CLASE EMPLEADO


public class Empleado extends Persona
{
   private String Cargo;
   private String Departamento;
  
    public Empleado(String Cargo, String Departamento,String Cedula, String Nombres, int Edad) {
        super(Cedula, Nombres, Edad);
        this.Cargo = Cargo;
        this.Departamento = Departamento;
    }

    @Override
    public void DatosInformativos() {
        super.DatosInformativos();
        System.out.println("Cargo: " + this.Cargo);
        System.out.println("Departamento: " + this.Departamento);
    }
   

    public String CalcularSueldo(int numHoras, double valorHora)
    {
      double sueldo = numHoras * valorHora;
      String cadSueldo = " Sueldo: " + String.valueOf(sueldo);
      return cadSueldo;
    }}

CAPTURAS


Danny Muñoz
Programa que dibuja una circunferencia en un panel de java esta es un pequeño ejercicio que permite al estudiante comenzar en la programacion grafica en java.



CLASE JFRAME

package appdibujarcirculocalculararea;

public class Principal extends javax.swing.JFrame {

    public Principal() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {}                      

    private void btngraficarActionPerformed(java.awt.event.ActionEvent evt) {                                           
       int Xo = Integer.parseInt(this.textX0.getText());
       int Yo = Integer.parseInt(this.texty0.getText());
       int X1 = Integer.parseInt(this.textX1.getText());
       int Y1 = Integer.parseInt(this.texty1.getText());

       panel1.setXo(Xo);
       panel1.setYo(Yo);
       panel1.setX1(X1);
       panel1.setY1(Y1);

       panel1.DibujarCirculo();

    }                                          

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Principal().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                    
    private javax.swing.JButton btncalcular;
    private javax.swing.JButton btngraficar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private appdibujarcirculocalculararea.Panel panel1;
    private javax.swing.JTextField textX0;
    private javax.swing.JTextField textX1;
    private javax.swing.JTextField texty0;
    private javax.swing.JTextField texty1;
    // End of variables declaration                  

}

CLASE PANEL

package appdibujarcirculocalculararea;

import java.awt.Graphics;
import java.awt.*;


public class Panel extends javax.swing.JPanel {

    private int Xo,Yo;
    private int X1,Y1;

    public void setX1(int X1) {
        this.X1 = X1;
    }

    public void setXo(int Xo) {
        this.Xo = Xo;
    }

    public void setY1(int Y1) {
        this.Y1 = Y1;
    }

    public void setYo(int Yo) {
        this.Yo = Yo;
    }


    public Panel() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );
    }// </editor-fold>                       

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        g.setColor(Color.red);
        g.drawOval(this.Xo, this.Yo, this.X1, this.Y1);
    }
    public void DibujarCirculo()
    {
      repaint();
    }

    // Variables declaration - do not modify                    
    // End of variables declaration                  

}

CAPTURAS



Danny Muñoz
Ejercicio que realiza la operacion matematica de dividir mediante restas sucesivas el numero de resta es el resultado.

CLASE PRINCIPAL

package Packdivi;
 import java.io.*;
public class Principal {

    public static InputStreamReader Leer= new InputStreamReader (System.in);
    public static BufferedReader Teclado = new BufferedReader (Leer);
    public static void main(String[] args)throws IOException {
      
        int a,b;
    System.out.println("ingrese el dividendo ");
       a=Integer.parseInt(Teclado.readLine());
       System.out.println("ingrese el divisor ");
       b=Integer.parseInt(Teclado.readLine());
     
      
      
        Restar Obj= new Restar(a,b);
      
        Obj.Resta();
        // TODO code application logic here
    }
}


CLASE RESTAS

package Packdivi;


public class Restar {

    private int divi;
    private int dvsor;

    public Restar(int divi, int dvsor) {
        this.divi = divi;
        this.dvsor = dvsor;
    }
  
  
    public void Resta(){
  
    int res=0;
  
    while(divi>=dvsor){
      
      
        divi=divi-dvsor;
        res++;
  
    }
    System.out.print(+res);
    System.out.print(".");
   System.out.print(+divi);
  
    }   
}

CAPTURAS



Danny Muñoz
Programa que eleva un numero a cualquier exponente que el usuario ingrese mediante sumas sucesivas.
CLASE PRINCIPAL

package Pckpoten;
import java.io.*;
public class Principal {

    public static InputStreamReader Leer= new InputStreamReader(System.in);
    public static BufferedReader Teclado= new BufferedReader(Leer);
    public static void main(String[] args) throws IOException{
        // TODO code application logic here
        int res,a,b;
        System.out.println("Ingrese la base");
        a=Integer.parseInt(Teclado.readLine());
        System.out.println("Ingrese el exponente");
        b=Integer.parseInt(Teclado.readLine());
        Potencia Obj= new Potencia(a,b);
        res=Obj.Elevar();
        System.out.println("El resultado es: "+res);
       
       
    }
}


CLASE POTENCIA

package Pckpoten;

public class Potencia {
    private int b;//base
    private int e;//exponente

    public Potencia(int b, int e) {
        this.b = b;
        this.e = e;
    }
   
   
    public int Elevar(){
    int r=0,n=1;
        for(int h=0;h<this.e;h++){
            r=0;
        for(int i=0;i<this.b;i++){
        r+=n;
        }
        n=r;
        }
    return r;
    }   
}



CAPTURAS


Danny Muñoz
Crear una aplicacion que permita transformar un numero que el usuario ingrese por teclado en sistema decimal a sistema binario o sistema octal.
CLASE PRINCIPAL

package Packtransformacion;

import java.io.*;

public class Principal {

    //Objetos Leer Datos Teclado.
 public static InputStreamReader Leer = new InputStreamReader(System.in);
 public static BufferedReader Teclado = new BufferedReader(Leer);

    public static void main(String[] args)throws IOException
    {
        int []p= new int [20];
        int []o= new int [20];
            Transformacion bin = new Transformacion();
        System.out.print("Ingrese valor ");
        int valor = Integer.parseInt(Teclado.readLine());
        bin.setValor(valor);
        System.out.print("Escoja 1 binario 2 octal");
        int v = Integer.parseInt(Teclado.readLine());
     
        switch(v){
           
            case 1:
        p=bin.TransformarBinario();
      for (int i=19;i>=0;i--){
          if (p[i]!=2){
       System.out.print(p[i]); }}
       break;  
            case 2:
      o=bin.TransformarOctal();
      for (int i=19;i>=0;i--){
          if (o[i]!=8){
       System.out.print(o[i]); }}
        break;
        }
       
       
       
        // TODO code application logic here
    }
}



CLASE TRANSFORMACION


package Packtransformacion;

public class Transformacion {

    private int valor;

    public Transformacion() {
        this.valor = 0;
           
    }

    public void setValor(int valor) {
        this.valor = valor;
    }
   
   
   
   
    public int [] TransformarBinario(){
    int a=0,b=0;
    int []r=new int[20];
    while (this.valor>0){
        r[b]=this.valor%2;
        this.valor=this.valor/2;
    b++;
    }
    while (b<20){
        r[b]=2;
    b++;
    }
    return r;
    }
   
    public int [] TransformarOctal(){
    int a=0,b=0;
    int []d=new int[20];
    while (this.valor>0){
        d[b]=this.valor%8;
        this.valor=this.valor/8;
    b++;
    }
    while (b<20){
        d[b]=8;
    b++;
    }
    return d;
    }
    
    }

CAPTURAS



Danny Muñoz
Crear una aplicacion que llene dos vectores llenandoles con numeros aleatorios y compruebe las teorias de los conjuntos : union, interseccion, diferencia, producto, complemento.

CLASE PRINCIPAL

package Packrandom;

import java.io.*;
public class Principal {

    public static InputStreamReader Leer = new InputStreamReader (System.in);
        public static BufferedReader Teclado = new BufferedReader (Leer);

    public static void main(String[] args) throws IOException {

        Vector miercoles = new Vector ();
       

       miercoles.LLenar();
       miercoles.Mostrar();
       System.out.println("Teoria de la union");
       miercoles.Union();
       System.out.println("Teoria de la Interseccion");
       miercoles.Interseccion();
       System.out.println("Teoria de la diferencia");
       miercoles.Diferencia();
       System.out.println("Teoria del producto");
       miercoles.Producto();
       System.out.println("Teoria del complemento");
       miercoles.Complemento();

    }
}


CLASE VECTOR

package Packrandom;
import java.io.*;
import java.util.Random;

public class Vector {
    public static InputStreamReader Leer = new InputStreamReader (System.in);
    public static BufferedReader Teclado = new BufferedReader (Leer);

     private int [] a=new int [5];
     private int [] b=new int [5];

    public Vector() {
        this.a[0]=0;
        this.b[0]=0;
    }

    public void LLenar(){
        int n=0,r=0,k=0;
    Random rnd =new Random();
    while(k<5){
    r=0;
    n = rnd.nextInt(10);
    for(int j=0;j<k;j++){
    if(n==this.a[j]){r++;}}      
    if(r==0){this.a[k]=n;
    k++;}
    }
    k=0;
    while(k<5){
    r=0;
    n = rnd.nextInt(10);
    for(int j=0;j<k;j++){
    if(n==this.b[j]){r++;}}      
    if(r==0){this.b[k]=n;
    k++;}
    }   }
   
    public void Mostrar() throws IOException{
    System.out.println("Primer vector ");
    for(int i=0;i<5;i++){
    System.out.println(this.a[i]);}
    System.out.println("Segundo vector ");
    for(int o=0;o<5;o++){
    System.out.println(this.b[o]);}
    }  

    public void Producto(){
    int [] c=new int [5];
    for (int h=0;h<5;h++){
    for(int i=0;i<5;i++){
     c[h]+=this.a[h]*this.b[i];}}
    for(int i=0;i<5;i++){
    System.out.println(c[i]);
    }}

 public void Union(){
 int [] x=new int [5];    
for(int i=0;i<5;i++){x[i]=this.b[i];}
for (int h=0;h<5;h++){
    for(int i=0;i<5;i++){
        if(this.a[h]==x[i]){x[i]=11;}  } }
for(int i=0;i<5;i++){System.out.println(this.a[i]);}
for(int i=0;i<5;i++){if(x[i]!=11)System.out.println(x[i]);}
}//union

public void Interseccion(){
    for (int h=0;h<5;h++){
    for(int i=0;i<5;i++){
        if(this.a[h]==this.b[i]){
        System.out.println(this.b[i]);
        }  } }}

public void Diferencia(){
int [] y=new int [5];   
for(int i=0;i<5;i++){y[i]=this.a[i];}
for (int h=0;h<5;h++){
    for(int i=0;i<5;i++){if(y[h]==this.b[i]){y[h]=11;}} }
for(int i=0;i<5;i++){if(y[i]!=11)System.out.println(y[i]);}
}

public void Complemento(){
int [] y=new int [5];   
for(int i=0;i<5;i++){y[i]=this.a[i];}
for (int h=0;h<5;h++){
    for(int i=0;i<5;i++){if(y[h]==this.b[i]){y[h]=11;}} }
for(int i=0;i<5;i++){if(y[i]!=11)System.out.println(y[i]);}
}


}//final

CAPTURAS



Danny Muñoz
Realizar un programa que realiza o simula las operaciones que realiza un vehiculo como lo son frenar, estacionar, acelerar, arrancar.


CLASE PRINCIPAL

package PackVehiculo;

import java.io.*;
public class Principal {
 public static InputStreamReader Leer = new InputStreamReader(System.in);
 public static BufferedReader Teclado = new BufferedReader(Leer);
   
    public static void main(String[] args) throws IOException
    {
          // TODO code application logic here
        int op;
        Vehiculo auto = new Vehiculo();
       
        System.out.println("VEHICULO");
        System.out.println("1. Arrancar");
        System.out.println("2. Acelerar");
        System.out.println("3. Frenar");
        System.out.println("4. Estacionar");
        System.out.println("5. Salir");
        System.out.println("Elija una accion");
            do{
        op=Integer.parseInt(Teclado.readLine());
        switch(op){
            case 1:
                auto.Arranque();
                break;
            case 2:
                auto.Acelerar();
                break;
            case 3:
                auto.Frenar();
                break;
            case 4:
                auto.Estacionar();
                break;
        }
       
        }while(op<5);
 
    }
}

CLASE VEHICULO

package PackVehiculo;


public class Vehiculo {
   
private int velocidad;

    public Vehiculo() {
        this.velocidad = 0;
    }

    public int Estacionar(){
    this.velocidad=0;
    System.out.println("El vehiculo esta estacionado");
    return this.velocidad;
    }
   
   
    public int Arranque(){   
    this.velocidad=10;
    System.out.println("Velocidad:   "+this.velocidad);
    return this.velocidad;
    }
   
   
   
    public int Acelerar(){
    this.velocidad=this.velocidad+10;
    System.out.println("Velocidad:   "+this.velocidad);
    return this.velocidad;
    }
   
    public int Frenar(){
    this.velocidad=0;
    System.out.println("Velocidad:   "+this.velocidad);
    return this.velocidad;
    }  
}
CAPTURAS


Danny Muñoz
Realizar un ejercicio que permita calcular la distancia entre dos puntos conocidos aplicando la formula matematica respectiva.

CLASE PRINCIPAL

package packDistancia;
import java.io.*;

public class Principal {
public static InputStreamReader Leer = new InputStreamReader(System.in);
    public static BufferedReader Teclado = new BufferedReader(Leer);
    public static void main(String[] args)throws IOException {
  
    System.out.println("ingrese x1");
     int a1  = Integer.parseInt(Teclado.readLine());
       System.out.println("ingrese x2");
     int a2  = Integer.parseInt(Teclado.readLine());
       System.out.println("ingrese y1");
     int b1  = Integer.parseInt(Teclado.readLine());
       System.out.println("ingrese y2");
     int b2  = Integer.parseInt(Teclado.readLine());
       
        Puntos objpunto = new Puntos(a1,a2,b1,b2);
       
        double res=objpunto.Generar(a1,a2,b1,b2);
       
        System.out.println(res);    }
}

CLASE PUNTOS

package packDistancia;

public class Puntos {
   
    private  int x1;
    private  int x2;
    private  int y1;
    private  int y2;

    public Puntos(int x1, int x2, int y1, int y2) {
        this.x1 = x1;
        this.x2 = x2;
        this.y1 = y1;
        this.y2 = y2;
    }
   
    public double Generar(int x1, int x2, int y1, int y2){
   
        double r;
        r=Math.sqrt(Math.pow((this.x2-this.x1),2)+Math.pow((this.y2-this.y1),2));
         return r;  }

}

CAPTURAS



Danny Muñoz
Crear un programa que permita realizar una cuenta de banco y que permita realizar las operaciones siguientes: retiro,deposito,consulta,transferencia.


CLASE PRINCIPAL

package Packbanco;
import java.io.*;
public class Principal {
 public static InputStreamReader Leer = new InputStreamReader(System.in);
 public static BufferedReader Teclado = new BufferedReader(Leer);
   
    public static void main(String[] args) throws IOException
    {
       
       
        // TODO code application logic here
        double t,x;
        int op;
        String c;
        // TODO code application logic here
        System.out.println("Ingrese nombre");
        c=Teclado.readLine();
        System.out.println("Ingrese su saldo");
        x=Integer.parseInt(Teclado.readLine());
        Cuenta cliente = new Cuenta(x,c);
        do{
        System.out.println("1 Deposito");
        System.out.println("2 Retiro");
        System.out.println("3 Consulta");
        System.out.println("4 Salir");
        System.out.println("Elija una opcion");
        op=Integer.parseInt(Teclado.readLine());
       
        switch(op){
            case 1:
        System.out.println("Ingrese deposito");
        t=Integer.parseInt(Teclado.readLine());
        cliente.Deposito(t);
                break;
            case 2:
         System.out.println("Ingrese retiro");      
         t=Integer.parseInt(Teclado.readLine());
         cliente.Retiro(t);
        
                break;
            case 3:
              cliente.consulta(); 
                break;
        }//switch
       
        }while(op<4);//while
           
    }
}

CLASE CUENTA

package Packbanco;
public class Cuenta {
   
     private double saldo;
     private String nombre;

    public Cuenta(double saldo,String nombre) {
        this.saldo = saldo;
        this.nombre= nombre;
    }
    public double Deposito(double t){
        this.saldo=this.saldo+t;
        return this.saldo;
    }

     public double Retiro(double t){
        if(this.saldo>=t){
        this.saldo=this.saldo-t;
        return this.saldo; }  
        else {System.out.println("Su saldo actual no le permite realizar esta transaccion");
        return this.saldo;}     
    }
    
    
     public void consulta (){
     System.out.println("Su saldo es "+this.saldo);
     }}

CAPTURAS



Danny Muñoz
Crear una aplicacion que genere 10 numeros aleatorios y muestre por pantalla cuales son primos.


CLASE PRINCIPAL

package packaleatorio;

import java.util.Random;


public class principal {


    public static void main(String[] args) {
        // TODO code application logic here

        Random rnd =new Random();
        Aleatorio viernes = new Aleatorio();
        for(int i=1; i<=10; i++)
        {
        int num = rnd.nextInt(30);
        viernes.setValor(num);
        if(viernes.VerificarSiNoPrimo())

             System.out.println("es un numero primo:  " + num);
        else
             System.out.println("no es numero primo:  " + num);

       
        }}}

CLASE ALEATORIO

package packaleatorio;

public class Aleatorio {
private int valor;

public Aleatorio(){

           this.valor=0;
}

    public void setValor(int valor) {
        this.valor = valor;
    }
public boolean VerificarSiNoPrimo()
{
    int cont=0;
    for (int p=1; p<=this.valor; p++)
    {

        if (this.valor % p ==0)
            cont++;
    }
    if (cont<=2)
        return true;
    else
        return false;
}}

CAPTURAS



Danny Muñoz
Ejercicio en el cual se ingrese 10 numeros por teclado y determinar cuantos y cuales son numeros perfectos.

CLASE PRINCIPAL

package pckNumeroPerfecto;
import java.io.*;

public class Principal
{
    public static InputStreamReader Leer = new InputStreamReader(System.in);
    public static BufferedReader Teclado = new BufferedReader(Leer);
   
    public static void main(String[] args) throws IOException
    {
        System.out.println("Ingrese 10 Valores...!");

        int num=0,cont=0;
       
        Perfecto miercoles = new Perfecto();

        for(int i=1;i<=10;i++)
        {
          num = Integer.parseInt(Teclado.readLine());
          if(miercoles.VerificarPerfecto(num))
          {
            System.out.println("Numero Perfecto= " + num);
            cont++;
          }
        }
        System.out.println("Existen Numeros Perfectos: " + cont);

       
    }

}

CLASE PERFECTO

package pckNumeroPerfecto;

public class Perfecto {
    private int valor;

    public Perfecto()
    {
      this.valor=0;
    }
    public boolean VerificarPerfecto(int valor)
    {
        this.valor = valor;
        int sum=0,t=1;
        while(t<this.valor)
        {
          if(this.valor % t == 0)
              sum+=t;
          t++;
        }
        if(sum==this.valor)
            return true;
        else
            return false;
    }

}

CAPTURAS



Danny Muñoz
Ejercicio en el cual se implementa la metodologia orientada  a objetos crear un constructor parametrizado ,crear un metodo que permita sumar dos numeros enteros ademas estos numeros deben ser ingresados por el usuario.
PRINCIPAL

package pckSumador;

import java.io.*;

public class Principal {
    //Objetos Leer Datos Teclado.
    public static InputStreamReader Leer = new InputStreamReader(System.in);
    public static BufferedReader Teclado = new BufferedReader(Leer);


  
    public static void main(String[] args) throws IOException
    {
        System.out.print("Ingrese valor 1: ");
        int valor1 = Integer.parseInt(Teclado.readLine());

        System.out.print("Ingrese valor 2: ");
        int valor2 = Integer.parseInt(Teclado.readLine());

        Sumador Obj1 = new Sumador(valor1,valor2);

        int resul = Obj1.GenerarSuma();

        System.out.println("Resulltado = " + resul);
       
    }}

CLASE SUMADOR

package pckSumador;

public class Sumador {

    //Atributos-variables de instancia.
    private int num1;
    private int num2;

   //Metodos (Constructor - Convencional).
    public Sumador(int num1, int num2)
    {
        this.num1 = num1;
        this.num2 = num2;
    }

    public Sumador()
    {
        this.num1=0;
        this.num2=0;
    }
    public int GenerarSuma()
    {
       int sum=this.num1 + this.num2;
       return sum;
    }
}

CAPTURAS

 
 
Danny Muñoz
 MULTIPLICACION DE MATRICES

El producto de dos matrices se puede definir sólo si el número de columnas de la matriz izquierda es el mismo que el número de filas de la matriz derecha. Si A es una matriz m×n y B es una matriz n×p, entonces su producto matricial AB es la matriz m×p (m filas, p columnas.




 PROGRAMA EN C# PARA LA MULTIPLICACION DE MATRICES



using System ;
using System.Collections.Generic ;
using System. Text ;
namespace MultiplicacionMatrices {
    class MultiplicacionMatrices {
        static void Main ( ) {
            Console. WriteLine ( "[Matriz 1]" ) ;
            Console. Write ( "Filas: " ) ;
            int f1 = int . Parse ( Console. ReadLine ( ) ) ;
            Console. Write ( "Columnas: " ) ;
            int c1 = int . Parse ( Console. ReadLine ( ) ) ;
            Console. WriteLine ( " \n [Matriz 2]" ) ;
            Console. Write ( "Filas: " ) ;
            int f2 = int . Parse ( Console. ReadLine ( ) ) ;
            Console. Write ( "Columnas: " ) ;
            int c2 = int . Parse ( Console. ReadLine ( ) ) ;
            int [ , ] Matriz1 = new int [ f1 + 1 , c1 + 1 ] ;
            int [ , ] Matriz2 = new int [ f2 + 1 , c2 + 1 ] ;
            int [ , ] Multiplicacion = new int [ f1 + 1 , c2 + 1 ] ;
            if ( c1 == f2 ) { Console. WriteLine ( " \n Datos [Matriz 1]: " ) ;
                for ( int i = 1 ; i <= f1 ; i ++ ) {
                    for ( int j = 1 ; j <= c1 ; j ++ ) {
                        Console. Write ( "Ingresa Dato (Fila: {0} - Columna: {1}): " , i, j ) ;
                        Matriz1 [ i, j ] = int . Parse ( Console. ReadLine ( ) ) ; } }
                Console. WriteLine ( "Datos [Matriz 2]: " ) ;
                for ( int i = 1 ; i <= f2 ; i ++ ) {
                    for ( int j = 1 ; j <= c2 ; j ++ ) {
                        Console. Write ( "Ingresa Dato (Fila: {0} - Columna: {1}): " , i, j ) ;
                        Matriz2 [ i, j ] = int . Parse ( Console. ReadLine ( ) ) ;
                    } }
                for ( int i = 1 ; i <= f1 ; i ++ ) {
                    for ( int j = 1 ; j <= c2 ; j ++ ) {
                        Multiplicacion [ i, j ] = 0 ;
                        for ( int z = 1 ; z <= c1 ; z ++ ) {
                            Multiplicacion [ i, j ] = Matriz1 [ i, z ] * Matriz2 [ z, j ] + Multiplicacion [ i, j ] ;
                        } } }
                Console. WriteLine ( "Multiplicacion de 2 Matrices" ) ;
                for ( int i = 1 ; i <= f1 ; i ++ ) {
                    for ( int j = 1 ; j <= c2 ; j ++ ) {
                        Console. Write ( "{0} " , Multiplicacion [ i, j ] ) ;
                    }
                    Console. WriteLine ( ) ;
                } } else { Console. WriteLine ( "Error: No se puede multiplicar las matrices" + " Columnas: {0}! = Filas: {1}" , c1, f2 ) ;
            }
            Console. Read ( ) ;
        } } }

FUNCIONAMIENTO DEL CODIGO

El programa funciona de la siguiente manera primero pide al usuario que ingrese las filas y las columnas que tendran las matrices a multiplicar luego se evalua una condicion mediante un if y la condicon es que el numero de columnas de la matriz 1 debe de ser igual al numero de filas de la matriz 2 si la condicion se cumple el programa pide al usuario que llene las matrices y esto se lo hace mediante for anidados luego despues de haberse llenado las matrices se procede a usar tres fors anidados para realizar la operacion matematica el for de z controlara la mayor parte de los procesos internos luego el for de j controlara el cambio de posiciones de la matiz de las columnas de la matriz 2 y por ultimo el for de i controlara el movimiento de las filas de la matriz 1 y de la matriz resultante al terminar este proceso y haberse obtenido la matriz resultante se procedera a mostrarla mediante dos for anidados y por ultimo el programa cuenta con un mensaje de error que se mostrara en caso de que los valores ingresados para las filas y las columnas no cumplan con la condicion del if.