Revista vectores y matrices
-
Upload
jessica-soraya -
Category
Documents
-
view
239 -
download
1
description
Transcript of Revista vectores y matrices
1
2
Revisión y Ortografía:
Jessica Jaque.
Coordinación:
Luis Tayupanda.
Cristian Guaman.
Arte y Diseño:
Jerson Carranza.
A medida que pasa el tiempo, avanza el desarrollo de la tecnología en todos sus campos y de los puntos más importantes se encuentra la programación o desarrollo de software.
El desarrollo de las aplicaciones se crea todos a través de un código fuente en cualquier lenguaje de alto nivel. Un ejempló es visual Basic 8.0 que contiene la aplicación C#.
Con este lenguaje se crea aplicaciones tan sencillas como la suma de dos números para niños que están aprendiendo, como también aplicaciones tan complejas por ejemplo “CONTROL DE PRODUCTOS DE UN SUPER MERCADO”, por lo cual se necesita guardar datos.
Por lo cual hay que saber matrices y vectores para poder almacenar los datos que necesitaremos.
3
Índice.
1. Matrices ............................................................................................................................................. 4
1.1. Concepto ...................................................................................................................................... 4
1.2. Declaración en C# ..................................................................................................................... 4
2. Vectores ............................................................................................................................................. 4
2.1. Concepto ...................................................................................................................................... 4
2.2. Declaración en C# ..................................................................................................................... 4
3. Aplicaciones en C# .......................................................................................................................... 5
3.1. Insertar una fila en una matriz ............................................................................................. 5
3.2. Leer una matriz cuadrática ................................................................................................. 11
3.3.Intercambio de sumatoria de los elementos de una matriz………………………………..…………...16
3.3. - .................................................................................................................................................... 20
3.4. ...................................................................................................................................................... 20
3.5. ...................................................................................................................................................... 20
3.6. ...................................................................................................................................................... 21
3.7. ...................................................................................................................................................... 21
3.8. .................................................................................................................................................... 21
3.9. ...................................................................................................................................................... 24
3.10. ......................................................................................................................................... 26
3.11. ......................................................................................................................................... 27
3.12. ......................................................................................................................................... 30
3.13. ......................................................................................................................................... 32
3.14. ......................................................................................................................................... 35
3.15. ......................................................................................................................................... 38
3.16. ......................................................................................................................................... 41
4
Matrices. Una matriz es un arreglo bidimensional, que se puede guardar varios datos de un solo tipo este sea de tipo: Entero, Decimal, o Cadenas. Las matrices tienen características, ejemplo:
Nombre. Tipo. Dimensión en el número de filas. Dimensión en el número de columnas. Por defecto se inicializa en cero.
En C# para declarar una matriz su sintaxis es:
Tipo [,] nombre = new tipo [Máxima Dimensión en columnas, Máxima en filas];
Ejemplo:
Int [,] matriz =new Int [10,10];
Vectores. Se los conoces como arreglos unidimensional a los vectores los cuales guardan información en espacio de memoria de la computadora de un solo tipo.
La declaración en C# es:
Int [ ] vector = new int [10];
5
Por: Jerson Carranza.
Código: 5125
Método de Insertar una
fila en una matriz.
Este método consiste en introducir una fila en la matriz cuadrática en la última posición, ya sea esta de numero con números aleatorios o ingresado por el usuario.
Diseño de Software.
Para esto hay que ponerle el nombre para cada herramienta que vamos utilizar para evitar confusiones.
6
Código fuente de Insertar una fila en una matriz.
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace insertar1fila { public partial class Form1 : Form { int[,] matriz = new int[3, 3]; int col = 0; int fil = 0; int con = 0; public Form1() { InitializeComponent(); } private void btn_no_Click(object sender, EventArgs e) { btn_si.Enabled = false; btn_no.Enabled = false; gbd.Visible = true; } private void btn_ing_Click(object sender, EventArgs e) { gbl.Visible = true; matriz[col, fil] = int.Parse(txt_num.Text); txt_mat.Text += matriz[col,fil] + "\t"; fil++; if (fil == 3) { col++; fil = 0; if (col == 3) { MessageBox.Show("Ya esta llena la matriz"); btn_leer.Enabled = false; gbdt.Visible = true; } } }
7
private void txt_num_TextChanged(object sender, EventArgs e) { string dim = txt_num.Text; for (int i = 0; i < dim.Length; i++) { if (dim[i] > = '0' && dim[i] <= '9') { btn_leer.Enabled = true; } else { txt_num.Text=""; } } } private void button1_Click(object sender, EventArgs e) { this.Close(); } private void btn_si_Click(object sender, EventArgs e) { btn_si.Enabled = false; Random ob = new Random(); txt_mat.Clear(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { matriz[i, j] = ob.Next(11); txt_mat.Text += matriz[i, j] + "\t"; } } gbl.Visible = true; gbdt.Visible = true; }
8
private void btn_ing_Click_1(object sender, EventArgs e) { btn_leer.Enabled = false; btn_no.Enabled = false; if (con == 0) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { txt_mat2.Text += matriz[i, j] + "\t"; } } } con = 1; matriz[col, fil] = int.Parse(txt_nnum.Text); txt_mat2.Text += matriz[col, fil] + "\t"; fil++; if (fil == 3) { MessageBox.Show("Ya esta llena la ultima fila de la matriz"); btn_rep.Enabled = true; btn_ing.Enabled = false; } } private void textBox1_TextChanged(object sender, EventArgs e) { string dim = txt_nnum.Text; for (int i = 0; i < dim.Length; i++) { if (dim[i] >= '0' && dim[i] <= '9') { btn_ing.Enabled = true; } else { txt_nnum.Text = ""; } } }
9
private void btn_2si_Click(object sender, EventArgs e) { btn_rep.Enabled = true; btn_sno.Enabled = false; btn_no.Enabled = false; Random on = new Random(); for (int i = 0; i <= 3; i++) { for (int j = 0; j < 3; j++) { if ((i == 3)) { txt_mat2.Text += on.Next(10) +"\t"; } else { txt_mat2.Text += matriz[i, j] + "\t"; } } } gbl.Visible = true; gbdt.Visible = true; } private void btn_sno_Click(object sender, EventArgs e) { btn_sno.Enabled = false; btn_no.Enabled = false; btn_2si.Enabled = false; btn_ing.Visible = true; txt_nnum.Visible = true; } private void btn_rep_Click(object sender, EventArgs e) { btn_rep.Enabled = false; txt_mat.Clear(); txt_mat2.Clear(); btn_leer.Enabled = true; btn_sno.Enabled = true; btn_2si.Enabled = true; btn_si.Enabled = true; btn_no.Enabled = true; gbl.Visible = false; gbdt.Visible = false; } private void Form1_Load(object sender, EventArgs e) { } } }
10
Funcionamiento de la aplicación de insertar una fila.
La aplicación de insertar una fila fue creada desde el punto de vista del usuario.
1) Para llenar la matriz que por defecto es de (3 X 3), puede de ser de dos maneras. la primera es que el usuario puede ingresar sus propios datos. La segunda es que el usuario llena la matriz con números aleatorio.
2) Se visualizan los datos en un cuadro de texto automáticamente. 3) Para insertar la fila en la matriz cuadrática también puede ser de dos maneras
diferentes. La primera es ingresar los datos aleatoriamente. La segunda es por usuario.
4) Salen los datos en una caja de texto automáticamente con la fila insertada. 5) Si desea repetir presiona el botón “Repetir” caso contrario puede salir con el
botón “Salir”.
Programa en Ejecución.
11
AplicAción pArA leer unA mAtriz cuAdráticA.
Para leer los datos de la matriz necesitamos una caja de texto o”Textbox” para que ingrese un numero y se habilitara el botón que se encuentra deshabilitado.
Y para mostrar los datos de esa matriz necesitaremos una caja de texto que sea solo de lectura y que este activado la opción de multilinea.
Diseño del software.
12
Código fuente para leer una matriz.
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace matriz { public partial class leermatriz : Form { int dm=0; int col=0; int fil=0; int[,] matriz = new int[10,10]; public leermatriz() { InitializeComponent(); } private void label1_Click(object sender, EventArgs e) { } private void leermatriz_Load(object sender, EventArgs e) { } private void btn_sal_Click(object sender, EventArgs e) { this.Close(); }
13
private void textBox1_TextChanged(object sender, EventArgs e) { string dim = txt_dim.Text; for (int i = 0; i < dim.Length; i++) { if (dim[i] >= '0' && dim[i] <= '9') { btn_dim.Enabled = true; } else { txt_dim.Text = ""; } } } private void txt_datos_TextChanged(object sender, EventArgs e) { string dat = txt_datos.Text; for (int i = 0; i < dat.Length; i++) { if (dat[i] >= '0' && dat[i] <= '9') { } else { txt_datos.Text = ""; } } } private void btn_dim_Click(object sender, EventArgs e) { dm = int.Parse(txt_dim.Text); txt_dim.Enabled = false; btn_dim.Enabled = false; txt_datos.Enabled = true;//Habilitar la caja de texto ingresar datos btn_dat.Enabled = true;// }
14
private void button2_Click(object sender, EventArgs e) { matriz[col, fil] = int.Parse(txt_datos.Text); fil++; if(fil == dm ) { col++; fil = 0; if (col == dm ) { MessageBox.Show("Ya esta llena la matriz"); txt_datos.Enabled = false; btn_dat.Enabled = false; btn_escri.Enabled = true; } } } private void btn_escri_Click(object sender, EventArgs e) { for (int i = 0; i < dm; i++) { for (int j = 0; j < dm; j++) { txt_mat.Text += matriz[i,j] + "\t"; } txt_mat.Text += "\n"; } } private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { } private void txt_mat_TextChanged(object sender, EventArgs e) { } } }
15
Funcionamiento de la aplicación para leer una matriz.
Al ejecutar el programa observamos que la caja de texto está habilitada y los otro botones y “textbox” están deshabilitados. A medida que se va escribiendo los datos se van habilitando la caja de texto y sus respectivos botones.
A continuación los pasos para que funcione la aplicación.
1) Ingresamos la dimensión de la matriz cuadrática. 2) Hacemos clic en el botón que se llama “Dimensión”. 3) Ingresamos los datos de la matriz uno por uno y damos clic en el botón
“Ingresar”. 4) Cuando ya llenamos la matriz nos sale un mensaje “La matriz ya está llena”. 5) Para visualizar los datos damos clic en el botón “Escribir”. 6) Aplastamos finalmente “Salir” para terminar la aplicación.
16
Aplicación para la sumatoria de los elementos de una matriz cuadrática.
Esta aplicación da como resultado la sumatoria de los elementos de una matriz cuadrática, para este formulario hemos utilizado tres caja de texto, la primera para ingresar la dimensión, la segunda para visualizar los datos de la matriz, la tercera para observar el resultado.
También se ha utilizado tres botones uno para ingresar la dimensión, otro para llenar la matriz aleatoriamente, y el ultimo para salir del programa.
Para más detalle le presentamos el grafico.
17
Código fuente de la aplicación para la sumatoria de los elementos de una matriz cuadrática.
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Sumatoria_de_una_matriz { public partial class Form1 : Form { int[,] matriz = new int[10, 10]; int dimension; int suma = 0; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void textBox2_TextChanged(object sender, EventArgs e) { string dim = txt_dim.Text; for (int i = 0; i < dim.Length; i++) { if (dim[i] >= '0' && dim[i] <= '9') { btn_ok.Enabled = true; } else { txt_dim.Text = ""; } } }
18
private void btn_ok_Click(object sender, EventArgs e) { txt_dim.Enabled = false; btn_ok.Enabled = false; btn_llenar.Enabled = true; dimension = int.Parse(txt_dim.Text); } private void btn_llenar_Click(object sender, EventArgs e) { int aux; suma = 0; Random oM = new Random(); txt_mat.Clear(); for (int i = 0; i < dimension; i++) { for (int j = 0; j < dimension; j++) { aux = oM.Next(10); suma = suma + aux; txt_mat.Text += aux + "\t"; } txt_mat.Text += "\n"; } btn_llenar.Enabled = false; gbd.Visible = true; btn_rep.Enabled = true; txt_sum.Clear(); txt_sum.Text += suma; } private void btn_sal_Click(object sender, EventArgs e) { this.Close(); } private void groupBox1_Enter(object sender, EventArgs e) { } private void txt_sum_TextChanged(object sender, EventArgs e) { }
19
private void btn_rep_Click(object sender, EventArgs e) { txt_dim.Enabled = true; txt_dim.Clear(); btn_rep.Enabled = false; txt_mat.Clear(); gbd.Visible = false; btn_llenar.Enabled = false; } private void lbl_sum_Click(object sender, EventArgs e) { } private void txt_mat_TextChanged(object sender, EventArgs e) { } } }
Funcionamiento del software.
Para que funcione este programa correctamente debemos seguir estos pasos:
1) Ingresamos la dimensión de la matriz cuadrática y presionamos el botón OK. 2) Para llenar los datos de la matriz automáticamente presionamos el botón
LLENAR y automáticamente se llena la matriz y sale el resultado. 3) Si usted desea repetir el programa presiona el botón repetir y repite el proceso
y si desea salir Presiona el botón SALIR.
20
Luis Rodrigo TayupandaTacuriCódigo: 4954
DISEÑO DEL SOFTWARE QUE PERMITIRA ORDENAR ASCENDENTEMENTE
LA TRIANGULAR SUPERIOR DE UNA MATRIZ
Como primer punto diseñamos la aplicación con sus respectivos nombres para poder tomar muy en cuenta los botones y los cuadros de textos y así proceder a la codificación.
Imprime la matriz llena
Imprime la matriz ordenada ascendentemente la
triangular S
Botón para imprimir la matriz Ingresa los valores a la matriz
Ingresa el número de columnas
Ingresa el número de filas
Botón para llenar la matriz
21
Este programa sirve para ordenar ascendentemente la triangular superior de una
matriz cuadrática en la cual primero guardamos los valores de la triangular superior en un vector ,luego con el método de la burbuja ordenamos ascendentemente el vector y finalmente pasamos los elementos ordenados a la triangular superior de la matriz
A continuación se presenta el código fuente en c# para ordenar ascendentemente
la triangular superior de una matriz cuadrática. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace leermat { publicpartialclassForm1 : Form { int [,] mat = newint[10,10]; int fil; int col; public Form1() { InitializeComponent(); } privatevoid Form1_Load(object sender, EventArgs e) { } privatevoid btn_leer_Click(object sender, EventArgs e) { fil = int.Parse(txt_nf.Text); txt_nf.Enabled = false;
22
} privatevoid txt_nf_TextChanged(object sender, EventArgs e) { } privatevoid btn_c_Click(object sender, EventArgs e) { col = int.Parse(txt_nc.Text); txt_nc.Enabled = false; txt_num.Enabled = true; } privatevoid btnnum_Click(object sender, EventArgs e) { Random ob=newRandom (); for (int j=0;j<col;j++) { for(int i=0;i<fil;i++) { mat[j, i] = ob.Next(20); } } } privatevoid btn_esc_Click(object sender, EventArgs e) { for (int j = 0; j < col; j++) { for (int i = 0; i < fil; i++) { listBox1.Items.Add(mat[j, i]); } } } privatevoid button1_Click(object sender, EventArgs e) { } privatevoid listBox1_SelectedIndexChanged(object sender, EventArgs e) {
23
} privatevoid btnc_Click(object sender, EventArgs e) { int aux = 0,p=0; int [] vec = newint[10]; for (int j = 0; j < col; j++) { for (int i = 0; i < fil; i++) { if ( i>j) { vec[p]= mat[j,i]; p++; } } } for (int i = 0;i<(p-1); i++) { for (int j = (i+1);j <(p-1);j++) { if(vec[i]> vec[j]) { aux=vec[i]; vec[i]=vec[j]; vec[j]=aux; } } } p =0; for (int j = 0; j < col; j++) { for (int i = 0; i < fil; i++) { if (i > j) { mat[j, i] = vec[p]; p++; } } } for (int j = 0; j < col; j++) { for (int i = 0; i < fil; i++) { listBox2.Items.Add(mat[j, i]); } } } privatevoid txt_num_TextChanged(object sender, EventArgs e)
24
{ } } }
DISEÑO DEL SOFTWARE PARA ELIMINAR UNA COLUMNA DE UNA MATRIZ
De igual forma realizamos el diseño de las aplicaciones para tomar en cuenta los elementos que vamos utilizar
Este programa sirve para eliminar una columna de una matriz no cuadrática, donde pedimos el número de la columna que desea eliminar, luego con procedimientos lógicos procedemos a pasar los valores de la columna que le sigue a la columna que desea eliminar
25
A continuación se presenta el código fuente en c# para eliminar una
columna deseada de una matriz no cuadrática. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Eliminar_columna { publicpartialclassForm1 : Form
Botón para llenar la matriz
Imprime la matriz llena
Botón para imprimir la matriz
Imprime la matriz sin la columna q eliminamos
Ingresa el número de la columna q va eliminar
Ingresa el número de columnas
Ingresa el número de filas
Ingresa los valores a la matriz
26
{ int [,] mat = newint[10,10]; int f; int c; int a; public Form1() { InitializeComponent(); } privatevoid label2_Click(object sender, EventArgs e) { c = int.Parse(textBox1.Text); textBox1.Enabled = false; } privatevoid button1_Click(object sender, EventArgs e) { for (int j = 0; j <c; j++) { for (int i = 0; i < f; i++) { listBox1.Items.Add( mat[j, i]); } } } privatevoid label3_Click(object sender, EventArgs e) { Random ob = newRandom(); for (int j = 0; j < c; j++) { for (int i = 0; i < f; i++) { mat[j, i] = ob.Next(10); } } } privatevoid label4_Click(object sender, EventArgs e) { a = int.Parse(textBox3.Text); textBox3.Enabled = false; } privatevoid label5_Click(object sender, EventArgs e) { f = int.Parse(textBox4.Text); textBox4.Enabled = false; textBox2.Enabled = true; } privatevoid button2_Click(object sender, EventArgs e) { for (int j = a; j < c; j++)
27
{ for (int i = 0; i < f; i++) { mat[j, i] = mat[(j + 1), i]; } } for (int j = 0; j < c; j++) { for (int i = 0; i < f; i++) { listBox2.Items.Add(mat[j, i]); } } } } }
DISEÑO DE UN SOFTWARE QUE PERMITE VERIFICAR SI UNA MATRIZ CUADRATICA ES UNIDAD
De la misma manera diseñamos la aplicación con sus respectivos nombres para poder tomar muy en cuenta los botones y los cuadros de textos y así proceder a la codificación correspondiente.
Este programa nos permitirá verificar si la matriz es unidad y para ello de cumplirse que todos elementos de la diagonal principal deben ser igual a uno.
Y para resolver este problema solo comparamos si el valor de la columna es igual al valor de la fila. Si lo es procedemos a comparar los elementos de la diagonal con el valor de uno.
28
A continuación se presenta el código fuente en c# para verificar si la matriz es unidad,.
using System;
using System.Collections.Generic;
using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Matriz_unidad { publicpartialclassmatriz : Form { int [,] mat = newint [10,10]; int f;
Ingresa el número de columnas
Ingresa el número de filas
Ingresa los valores a la matriz Imprime la matriz llena
Botón para llenar la matriz
Botón para verificar
Si es M.unidad
Mensaje Box para
Indicar si es o no Matriz unidad
29
int c; public matriz() { InitializeComponent(); } privatevoid label2_Click(object sender, EventArgs e) { c = int.Parse(textBox1.Text); textBox1.Enabled = false; } privatevoid label3_Click(object sender, EventArgs e) { f = int.Parse(textBox2.Text); textBox2.Enabled = false; textBox3.Enabled = true; } privatevoid button1_Click(object sender, EventArgs e) { for (int j = 0; j < c; j++) { for (int i = 0; i < f; i++) { listBox1.Items.Add(mat[j,i]); } } } privatevoid label4_Click(object sender, EventArgs e) { Random ob = newRandom(); for (int j = 0; j < c; j++) { for (int i = 0; i < f; i++) { mat[j, i] = ob.Next(10); } } } privatevoid button2_Click(object sender, EventArgs e) { int s =0; for (int j = 0; j < c; j++) { for (int i = 0; i < f; i++) { if (j == i) {
30
if (mat[j, i] == 1) s++; } } } if (s == c) MessageBox.Show("Si es Matriz unidad"); else MessageBox.Show("No es una matriz unidad"); } privatevoid button3_Click(object sender, EventArgs e) { textBox1.Clear(); textBox1.Enabled = true; textBox2.Clear(); textBox2.Enabled = true; textBox3.Clear(); textBox1.Focus(); } } }
31
Resolución de una “Matriz Cuadrática”
Nombre: AngelChaluisa.
Codigo: “4600”.
A continuación vamos a ver una delas características y denominaciones de una Matriz.
Para lo cual se va a centrar específicamente en la “Matriz Cuadrática”
Una matriz cuadrática es cuando el número de filas es igual al número de columnas, para declarar la misma en C# es el siguiente código.
Declaracion:
Int[,]Matriz=new int[#f,#c];
De la matriz cuadrática se puede hacer varios procesos, en este caso se procede a:
a) Lectura y escritura: En un formulario se hace su declracion respectiva.
int[,] matriz = new int[3, 3]; int i=0; int j=0;
Su tamaño está definida por el programador.
En le Button “Ingreso” su codificación es.
for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) {
32
listBox1.Items.Add(matriz[i,j]); } } Para el Button de la “escritura” :
matriz[i,j] = int.Parse(textBox1.Text); j++; if (j >= 3)
{ i++; j = 0;
Form1
33
b) Luego de la lectura se realiza busco el menor ellemento que esta dentro de la matriz.
En un formulario se hace su declracion respectiva.
int[,] matriz = new int[3, 3]; int i=0; int j=0;
Su tamaño está definida por el programador.
En le Button “Ingreso” su codificación es.
for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { listBox1.Items.Add(matriz[i,j]); } } Para el Button de la “escritura” :
matriz[i,j] = int.Parse(textBox1.Text); j++; if (j >= 3)
{ i++; j = 0; Se agrega un Button al formulario de la solucion anterior Donde diga “Calculo del Menor elemento”.
i = 0; j = 0; int gr = matriz[i,j]; for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { if (gr > matriz[i, j])
34
gr = matriz[i, j]; } }
} } tBx2.Text = gr.ToString();
De la misma manera se procede para el calculo del mayor elemento,
Siempre y cuando cambie la condición. Form2
35
C) Para la sumatoria de los elementos que están dentro de una matriz . En un formulario se hace su declracion respectiva.
int[,] matriz = new int[3, 3]; int i=0; int j=0;
Su tamaño está definida por el programador.
36
En le Button “Ingreso” su codificación es. for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { listBox1.Items.Add(matriz[i,j]); } } Para el Button de la “escritura” :
matriz[i,j] = int.Parse(textBox1.Text); j++; if (j >= 3)
{ i++; j = 0;
Agregamos un Button para la suma y codifico de la siguiente manera.
i = 0; j = 0; int suma = matriz[i,j]; for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { Suma = suma +matriz[i, j]; } }
} } tBx3.Text = gr.ToString();
37
38
Realizado por: Jessica Jaque
Código: 5382
SOFTWARE QUE PERMITE INTERCAMBIAR LOS ELEMENTOS DE DOS FILAS EN UNA MATRIZ N X M
Diseño del Software
Como primer punto diseñamos la aplicación con sus respectivos nombres para poder tomar muy en
cuenta los botones y los cuadros de textos y así proceder realizar la codificación necesaria para realizar lo
requerido.
Funcionamiento del Software
Ingresar los elementos la dimensión de la matriz con filas=n, columnas=m.
txbleefila
btnIngresar
btnEscribir
btnInterca
Btnsalir
Listbox txbleecolu
txbleeElem
39
Ingresar los elementos de la matriz.
-Para ello el cursor se encontrara en el texbox requerido.
-Dar un clic el botón ingresar.
-De este modo se ingresaran uno a uno los elementos.
Dar un clic al botón intercambiar.
Posteriormente un clic para listar los elementos en el botón escribir.
Para utilizarlo nuevamente serramos la aplicación y ejecutamos nuevamente.
Intercambiar los elementos de dos filas en una matriz. A continuación se presenta el código fuente en C# necesarios para realizar el software.
using System;
40
using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WinAppIngresarUnaColumna { publicpartialclassForm1 : Form { int[,] matriz = newint[5, 5]; int fila = 0, columna = 0; int f = 0, c = 0; public Form1() { InitializeComponent(); } privatevoid label2_Click(object sender, EventArgs e) { } privatevoid button4_Click(object sender, EventArgs e) { for(int i=0;i<fila;i++) for (int j=0;j<columna;j++) listBox1.Items.Add(matriz[i,j]); } privatevoid btnIngresar_Click(object sender, EventArgs e) { int elemento = int.Parse(txbLeeElementos.Text); if (f < fila) { matriz[f, c] = elemento; txbLeeElementos.Clear(); txbLeeElementos.Focus(); } c++; if (c == columna) { c = 0; f++; } if (f==fila) { btnIngresar.Enabled=false; txbLeeElementos.Enabled=false; } } privatevoid btnSalir_Click(object sender, EventArgs e) {
41
this.Close(); } privatevoid txbLeeFilas_TextChanged(object sender, EventArgs e) { if ((int.Parse(txbLeeFilas.Text)) > 0 && (int.Parse(txbLeeFilas.Text)) <= 5) { fila = int.Parse(txbLeeFilas.Text); txbLeeFilas.Enabled = false; } } privatevoid txbLeeColumna_TextChanged(object sender, EventArgs e) { if ((int.Parse(txbLeeColumna.Text) > 0) && (int.Parse(txbLeeColumna.Text)) <= 5) { columna = int.Parse(txbLeeColumna.Text); txbLeeColumna.Enabled = false; } } privatevoid btmInIntercambiar_Click(object sender, EventArgs e) { int aux =0; for (int i = 0; i < columna; i++) for (int j = 0; j < 1;j++ ) { aux = matriz[0, i]; matriz[j, i] = matriz[(j+1), i]; matriz[(j+1), i] = aux; } } privatevoid Form1_Load(object sender, EventArgs e) { } } }
SOFTWARE QUE PERMITE INGRESAR UNA COLUMNA EN UNA MATRIZ N X M.
Diseño del Software
Como primer punto diseñamos la aplicación con sus respectivos nombres para poder tomar muy en
cuenta los botones y los cuadros de textos y así proceder a realizar la codificación.
42
Agregar una columna a la matriz. Para agregar una nueva columna a la matriz se toma en cuenta con prioridad la dimensión de la misma, para de este no sobresalir al límite es decir al rango máximo de la matriz ingresada. Como se insertara una columna también se incrementara la cantidad de la variable columna. Para posteriormente proceder a ingresar los elementos. El beneficio de poder ingresar una nueva fila a la matriz nos ayuda a que en algún momento requerido por el usuario se pueda incrementar algún dato.
A continuación se presenta el código fuente en C# que permite ingresar los elementos de una columna agregada en una matriz.
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WinAppIngresarColumna { publicpartialclassForm1 : Form { int [,] matriz =newint [5,5]; int fila = 0, columna = 0; int f = 0, c = 0; public Form1() { InitializeComponent(); }
Txbleefila
Txbleecolumna
Btningresar
btnAgregar
Btnescribir
txbleeelement
Btnsalir
Lisbox1
43
privatevoid txbLeeFila_TextChanged(object sender, EventArgs e) { if ((int.Parse(txbLeeFila.Text) > 0) && (int.Parse(txbLeeFila.Text) <= 5)) { fila = int.Parse(txbLeeFila.Text); txbLeeFila.Enabled = false; } } privatevoid txbLeeColumna_TextChanged(object sender, EventArgs e) { if ((int.Parse(txbLeeColumna.Text) > 0) && (int.Parse(txbLeeColumna.Text) <= 5)) { columna = int.Parse(txbLeeColumna.Text); txbLeeColumna.Enabled = false; } } privatevoid btnIngresar_Click(object sender, EventArgs e) { int elemento = int.Parse(txbLeeElementos.Text); if (f < fila) { matriz[f,c] = elemento; txbLeeElementos.Clear(); txbLeeElementos.Focus(); c++; } if (c == columna) { c = 0; f++; } if (f == fila) { btnIngresar.Enabled = false; } } privatevoid btnEscribir_Click(object sender, EventArgs e) { for (int f = 0; f < fila; f++) for (int c = 0; c < columna; c++) { listBox1.Items.Add(matriz[f, c]); } } privatevoid btnAgregar_Click(object sender, EventArgs e) { if (columna < 5) { columna++; btnIngresar.Enabled = true;
44
} f = 0; if (f < fila) { matriz[f, c] = int.Parse (txbLeeElementos.Text); txbLeeElementos.Clear(); txbLeeElementos.Focus(); c++; } if (c == columna) { c = 0; f++; } if (f == fila) { btnIngresar.Enabled = false; } } privatevoid btnSalir_Click(object sender, EventArgs e) { this.Close(); } } }
Funcionamiento del Software
Ingresar primero la dimensión de la matriz con filas= n, columnas=m.
Ingresar uno de los elementos.
Posteriormente dar un clic en el botón agregar.
El botón Ingresar se habilita.
Luego se ingresara los elementos de la columna agregada.
Posteriormente un clic para listar los elementos
Para utilizarlo nuevamente serramos la aplicación y ejecutamos nuevamente.
45
Agregar una columna a la matriz. A continuación se presenta el código fuente en C# que permite ingresar los elementos de una columna agregada en una matriz.
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WinAppIngresarColumna { publicpartialclassForm1 : Form { int [,] matriz =newint [5,5]; int fila = 0, columna = 0; int f = 0, c = 0; public Form1()
46
{ InitializeComponent(); } privatevoid txbLeeFila_TextChanged(object sender, EventArgs e) { if ((int.Parse(txbLeeFila.Text) > 0) && (int.Parse(txbLeeFila.Text) <= 5)) { fila = int.Parse(txbLeeFila.Text); txbLeeFila.Enabled = false; } } privatevoid txbLeeColumna_TextChanged(object sender, EventArgs e) { if ((int.Parse(txbLeeColumna.Text) > 0) && (int.Parse(txbLeeColumna.Text) <= 5)) { columna = int.Parse(txbLeeColumna.Text); txbLeeColumna.Enabled = false; } } privatevoid btnIngresar_Click(object sender, EventArgs e) { int elemento = int.Parse(txbLeeElementos.Text); if (f < fila) { matriz[f,c] = elemento; txbLeeElementos.Clear(); txbLeeElementos.Focus(); c++; } if (c == columna) { c = 0; f++; } if (f == fila) { btnIngresar.Enabled = false; } } privatevoid btnEscribir_Click(object sender, EventArgs e) { for (int f = 0; f < fila; f++) for (int c = 0; c < columna; c++) { listBox1.Items.Add(matriz[f, c]); } } privatevoid btnAgregar_Click(object sender, EventArgs e) { if (columna < 5)
47
{ columna++; btnIngresar.Enabled = true; } f = 0; if (f < fila) { matriz[f, c] = int.Parse (txbLeeElementos.Text); txbLeeElementos.Clear(); txbLeeElementos.Focus(); c++; } if (c == columna) { c = 0; f++; } if (f == fila) { btnIngresar.Enabled = false; } } privatevoid btnSalir_Click(object sender, EventArgs e) { this.Close(); } } }
-SOFTWARE QUE PERMITE ELIMINAR UN ELEMENTO DE UN VECTOR
48
Funcionamiento del Software
Ingresar los elementos necesarios (<=10).
Ingresar uno de los elementos a eliminar.
Dar un clic al botón eliminar
Posteriormente un clic para listar los elementos
Para utilizarlo nuevamente serramos la aplicación y ejecutamos nuevamente.
Btneliminar
Btbingresar
Listbox1
Btnsalir Btnescribir
Txbeliminar
Txbleer
49
Eliminar un elemento de un vector. A continuación se presenta el código fuente en C# que permite eliminar un elemento de un vector.
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WinAppEliminarElementoDeVector { publicpartialclassForm1 : Form { int [] vector= newint[11]; int i = 0; public Form1() { InitializeComponent(); } privatevoid Form1_Load(object sender, EventArgs e) { } privatevoid button1_Click(object sender, EventArgs e) { vector[i] = int.Parse(txbleer.Text); if (i == 5) { btnIngresar.Enabled = false; txbleer.Enabled = false; } i++; }
50
privatevoid btnEscribir_Click(object sender, EventArgs e) { for (int j = 0; j <i; j++) listBox1.Items.Add(vector[j]); } privatevoid btnSalir_Click(object sender, EventArgs e) { this.Close(); } privatevoid btnEliminar_Click(object sender, EventArgs e) { int n = i; for (int j = 0; j <= n; j++) { if (vector[j] == int.Parse(txbeliminar.Text)) { for (int k = j; k < (n); k++) { vector[k] = vector[k+ 1]; } i--; } } } } }
NOMBRE: CRISTIAN GUAMAN - 5120
MATRIZ TRIANGULAR SUPERIOR private void BtnConvertir_Click(object sender, EventArgs e) { { int[,] matriz = new int[3, 3]; int cont = 0; int i = 0, j = 0; int aux; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) { if (j<i) matriz[i,j]=0;
51
} }
MATRIZ TRIANGULAR INFERIOR ORDENAR ASCENDENTEMENTE
private void BtnConvertir_Click(object sender, EventArgs e) { int[,] matriz = new int[3, 3]; int cont = 0; int i = 0, j = 0; int aux; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) if (j>i) matriz[i,j]=0; } private void BtnOrdenar_Click(object sender, EventArgs e) { for (int k = 0; k < 3; k++) for (int l = 0; l < 3; l++) for (int m = 0; m < 3; m++) for (int n = 0; n < 3; n++)
if ((matriz[k, l] != 0)&&(matriz[m,n]!=0)) { if (matriz[k, l] < matriz[m, n]) { aux = matriz[k,l]; matriz[k,l] = matriz[m,n]; matriz[m,n] = aux; } } }
52
ELIMINAR UNA COLUMNA DE UNA MATRIZ
private void BtnConvertir_Click(object sender, EventArgs e) { string datos = textBox1.Text; int numero = int.Parse(datos); if (numero < 3) { for (int i = 0; i < 3; i++) for (int j = numero; j < 3; j++) { matriz[i,j] = matriz[i,j++]; matriz[i, j+1] = matriz[i,j]; } } }
53