Вы находитесь на странице: 1из 54

Cuaderno de Computacin II 2010

COMPUTACION II

Fanny Alquinga Alejandra Fonseca


2010-06-17

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 1

Cuaderno de Computacin II 2010

ndice
Temas PAGINA

CAPTULO IV: 4. Programacin Visual.3 4.2 Objetivos....4 4.3 Introduccin...5

4.4 Objetos y Eventos.9


4.3.1 Ejemplos10

4.4 Funciones Recursivas.31 4.5 Utilizacin de Pila (Stack) de la Memoria34 4.5.1 Ejemplos.36 4.6 Manejo de Arreglos..41 4.6.1 Ejemplos.41 4.7 Grficos con GDI+48 4.7.1 Ejemplo49
4.8 Glosario54

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 2

Cuaderno de Computacin II 2010

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 3

Cuaderno de Computacin II 2010

4.1

OBJETIVOS:

Mediante el estudio de este capitulo se aplicar con mayor profundidad los conceptos bsicos de programacin.

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 4

Cuaderno de Computacin II 2010

4.2

INTRODUCCIN.

V.C# V.Basic
(Lo mejor de c, C++, Java, V. Basic)

V.C++

V JAVA
(Aberracin del Java de SUN Microsystems)

IDE
(Integrated Development Enviroment) Ambiente de Desarrollo Integrado

.NET Framework
(Infraestructura de Desarrollo de Software)

XBOX Aplicaciones de Escritorio (Desktop)

Aplicaciones Cliente/Servido r

Aplicaciones Web (HTML,XML, ASP,ASPX)

Aplicaciones Mviles

Aplicaciones Embebidas (Firmusare)

Aplicaciones de Videojuegos (Direct X, XnA) Plataforma Sistemas Operativos Windows Autor: Fanny Alquinga-Alejandra Fonseca. Pgina 5

Cuaderno de Computacin II 2010


Comprende cuatro lenguajes de programacin en uno

.NET Framework (Infraestructura de desarrollo) V. Basic V. C# V. C++ V. Java(aberracion del Java de SUN Microsystems)

IDE (Integrated Development Environment)-(Ambiente de desarrollo Integrado) Plataforma Sistema Operativo Windows .NET Framework (Infraestructura de desarrollo) Aplicaciones de Videojuegos (Direct X, XNA)->Game Engine Aplicaciones de Escritorio (Desktop) Aplicaciones de Web(HTML, XML, ASP, ASPX) Aplicaciones Cliente/Servidor Aplicaciones Mobiles Aplicaciones Embebidas(Firmware)

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 6

Cuaderno de Computacin II 2010


Plataforma Sistema Operativo Windows

En el WORK ENVIRONMENT (Ambiente de Trabajo), tenemos:

Para iniciar Visual Studio seguimos los siguientes pasos:

1. Se lo busca en programas y se elige con el lenguaje de programacin que se desee, trabajaremos con C

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 7

Cuaderno de Computacin II 2010

2. Archivo 3. Nuevo 4. Nuevo Proyecto 5. Windows Aplication 6. Nombrar (WinAppPrueba)

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 8

Cuaderno de Computacin II 2010


4.3 OBJETOS Y EVENTO Clase Derivada de la clase Form Formulario (Form) Datos Miembro (Atributos) Propiedades(Properties) Funciones Miembro (Mtodos) Eventos(Evento)

Propiedades del Formulario. Name: Form1 Text: Formulario de Prueba

Propiedades del Botn(Button) Name: Button1 Text: Mostrar Mensaje Image: [Cargar imagen]

Backcolor: (Control System) Font: Sems Serif

Uso de Prefijos para nombres de objetos Objeto Form Button TextBox GroupBox Timer Label ListBox ComboBox Prefijo frm btn txt grb tmr lbl lst cmb Pgina 9

Autor: Fanny Alquinga-Alejandra Fonseca.

Cuaderno de Computacin II 2010

4.3.1 EJEMPLOS: HOLA MUNDO (con botones)


using using using using using using using System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Text; System.Windows.Forms;

namespace hola_mundo { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { MessageBox.Show ("Hola Mundo"); } private void button2_Click(object sender, EventArgs e) { Close(); } } }

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 10

Cuaderno de Computacin II 2010


PROGRAMA QUE CALCULA EL REA Y EL PERMETRO DE UN CRCULO

Pasos para elaborar el Programa:

1. Modifico el nombre del programa

(Name)

frmCirculo

2. Busco Group Box en la caja de herramientas, Ingreso 3 de ellos y les quito el texto 3. En el primer Group Box, ingreso 1 Label y 1 Caja de Texto 4. Modifico el texto del primer label: Ingrese el valor del radio 5. Ingreso 3 botones en el segundo Group Box 6. En el tercer Group Box ingreso dos labels y dos cajas de texto 7. En el label 2 modifico el texto: Permetro del Crculo 8. En el label 3 modifico el texto: rea del Crculo 9. En el segundo Group Box ingreso 3 botones 10. Selecciono el primer botn y le modifico su texto: Calcular 11. Coloco un & para abreviatura de la tecla ALT+ (la letra seleccionada(C)) realizara la funcin del botn 12. Selecciono el segundo botn y le modifico su texto: Resetear 13. Coloco un & para abreviatura de la tecla ALT+ (la letra seleccionada(R)) realizara la funcin del botn 14. Selecciono el segundo botn y le modifico su texto: Salir

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 11

Cuaderno de Computacin II 2010


15. Coloco un & para abreviatura de la tecla ALT+ (la letra seleccionada(S)) realizara la funcin del botn 16. Modifico los nombres de las cajas de texto que voy a utilizar a) Primera caja de texto: txtRadio b) Segunda caja de texto: txtPerimetro c) Tercera caja de texto: txtArea 17. Modifico los nombres de los botones que voy a utilizar a) Primer botn: btnCalcular b) Segundo botn: btnResetear c) Tercer botn: btnSalir 18. Ahora modifico el cdigo del botn calcular:

19. Declaramos las variables: prvate doubl radio, permetro, area; 20. Inicializamos los datos txtRadio.Text=0.0; txtPerimetro.Text=0.0; txtArea.Text=0.0; 21. Ahora leemos el radio: radio=float.Parse(txtRadio.Text); 22. Realizamos los clculos a) Del permetro: perimetro=2*Math.PI*radio; b) Del rea: Autor: Fanny Alquinga-Alejandra Fonseca. Pgina 12

Cuaderno de Computacin II 2010


area=Math.PI*Math.Pow(radio,2); 23. Para imprimir en la caja de texto: a) El permetro tenemos: txtPerimetro.Text=perimetro.ToString(); b) El rea tenemos: txtArea.Text=area.ToString();

24. Modificamos el cdigo del botn Resetear: InicializaDator(); 25. Ahora modifico el cdigo de salir: Close();
CODIGO FUENTE Y SALIDA DEL PROGRAMA
System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Text; System.Windows.Forms;

using using using using using using using

namespace WinAppAle { public partial class Form1 : Form { private double radio; private double area; private double perimetro; public Form1() { InitializeComponent(); } private void InicializarDatos() { this.txtRadio.Text = "0.0"; txtPerimetro.Text="0.0"; txtArea.Text="0.0"; }

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 13

Cuaderno de Computacin II 2010


private double PerimetroCirculo() { radio = double.Parse(txtRadio.Text); return(2 * Math.PI * radio); } private double AreaCirculo() { radio = double.Parse(txtRadio.Text); return(Math.PI * Math.Pow(radio, 2)); } private void btnCalcular_Click(object sender, EventArgs e) { perimetro = PerimetroCirculo(); area = AreaCirculo(); txtPerimetro.Text = perimetro.ToString(); txtArea.Text = area.ToString(); } private void btnResetear_Click(object sender, EventArgs e) { InicializarDatos(); } private void btnSalir_Click(object sender, EventArgs e) { Close(); } private void Form1_Load(object sender, EventArgs e) { InicializarDatos(); } } }

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 14

Cuaderno de Computacin II 2010


PROGRAMA QUE CALCULA EL REA Y EL PERMETRO DE LAS FIGURAS GEOMETRICAS Explicacin de Tringulo

b a A c B

Teorema: un tringulo existe s y slo si la suma de cualquiera de sus dos lados es mayor que el tercer lado (a+b>c)&&(b+c>a)&&(a+c>b) rea=(p*(p-a)*(p-b)*(p-c))

DISEO DEL MEN:

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 15

Cuaderno de Computacin II 2010


CODIGO FUENTE Y SALIDA DEL PROGRAMA

MEN:

using using using using using using using

System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Text; System.Windows.Forms;

namespace Menu { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void btnCirculo_Click(object sender, EventArgs e) { frmCirculo Obj = new frmCirculo(); Obj.Show(); } private void btnCuadrado_Click(object sender, EventArgs e) { frmCuadrado Obj = new frmCuadrado(); Obj.Show(); } private void btnRectangulo_Click(object sender, EventArgs e) { frmRectangulo Obj = new frmRectangulo(); Obj.Show(); } private void btnTriangulo_Click(object sender, EventArgs e) { frmTriangulo Obj = new frmTriangulo(); Obj.Show(); } private void btnSalir_Click(object sender, EventArgs e) { Close(); }

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 16

Cuaderno de Computacin II 2010


} }

CIRCULO:

using using using using using using using

System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Text; System.Windows.Forms;

namespace Menu { public partial class frmCirculo : Form { private double perimetro, area, radio; public frmCirculo() { InitializeComponent(); } private double PerimetroCirculo() { return (2 * Math.PI * radio); } private double AreaCirculo() { return (Math.PI * Math.Pow(radio, 2)); } private void InicializarDatos() { txtArea.Text = "0.0"; txtPerimetro.Text = "0.0"; txtRadio.Text = "0.0"; } private void btnCalcular_Click(object sender, EventArgs e) { radio = float.Parse(txtRadio.Text); perimetro = PerimetroCirculo(); area = AreaCirculo(); txtPerimetro.Text = perimetro.ToString(); txtArea.Text = area.ToString(); } private void btnResetear_Click(object sender, EventArgs e) { InicializarDatos(); } private void btnSalir_Click(object sender, EventArgs e)

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 17

Cuaderno de Computacin II 2010


{ Close(); } private void frmCirculo_Load(object sender, EventArgs e) { InicializarDatos(); } } }

CUADRADO:
using using using using using using using System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Text; System.Windows.Forms;

namespace Menu { public partial class frmCuadrado : Form { private double lado, area, perimetro; public frmCuadrado() { InitializeComponent(); } private double PerimetroCuadrado() { return (4 * lado); } private double AreaCuadrado() { return (lado*lado); } private void InicializarDatos() { txtArea.Text = "0.0"; txtPerimetro.Text = "0.0"; txtLado.Text = "0.0"; } private void btnCalcular_Click(object sender, EventArgs e) { lado = float.Parse(txtLado.Text); area = AreaCuadrado(); perimetro = PerimetroCuadrado(); txtPerimetro.Text = perimetro.ToString(); txtArea.Text = area.ToString(); }

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 18

Cuaderno de Computacin II 2010


private void btnResetear_Click(object sender, EventArgs e) { InicializarDatos(); } private void btnSalir_Click(object sender, EventArgs e) { Close(); } private void frmCuadrado_Load(object sender, EventArgs e) { InicializarDatos(); } } }

RECTANGULO:

using using using using using using using

System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Text; System.Windows.Forms;

namespace Menu { public partial class frmRectangulo : Form { private double lado1, lado2, area, perimetro; public frmRectangulo() { InitializeComponent(); } private double PerimetroRectangulo() { return ((2* lado1)+(2*lado2)); } private double AreaRectangulo() { return (lado1 * lado2); } private void InicializarDatos() { txtArea.Text = "0.0"; txtPerimetro.Text = "0.0"; txtLado1.Text = "0.0"; txtLado2.Text = "0.0"; } private void btnCalcular_Click(object sender, EventArgs e) {

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 19

Cuaderno de Computacin II 2010


lado1 = float.Parse(txtLado1.Text); lado2 = float.Parse(txtLado2.Text); area = AreaRectangulo(); perimetro = PerimetroRectangulo(); txtArea.Text = area.ToString(); txtPerimetro.Text = perimetro.ToString(); } private void btnResetear_Click(object sender, EventArgs e) { InicializarDatos(); } private void btnSalir_Click(object sender, EventArgs e) { Close(); } private void frmRectangulo_Load(object sender, EventArgs e) { InicializarDatos(); } } }

TRIANGULO:

using using using using using using using

System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Text; System.Windows.Forms;

namespace Menu { public partial class frmTriangulo : Form { private double lado1, lado2, lado3, area, perimetro; public frmTriangulo() { InitializeComponent(); } private void InicializarDatos() { txtArea.Text = "0.0"; txtPerimetro.Text = "0.0"; txtLado1.Text = "0.0"; txtLado2.Text = "0.0"; txtLado3.Text = "0.0"; } private double PerimetroTriangulo() { return((lado1)+(lado2)+(lado3)); } private double AreaTriangulo()

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 20

Cuaderno de Computacin II 2010


{ double p; p = ((PerimetroTriangulo()) / 2); area=(Math.Sqrt(p*(p-lado1)*(p-lado2)*(p-lado3))); return (area); } private void btnCalcular_Click(object sender, EventArgs e) { bool bandera = false; try { lado1 = float.Parse(txtLado1.Text); lado2 = float.Parse(txtLado2.Text); lado3 = float.Parse(txtLado3.Text); } catch (Exception caught) { MessageBox.Show("Error en el Ingreso de Datos" + caught, "Mensaje de Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error); InicializarDatos(); return; } if (lado1>0 && lado2>0 && lado3>0) { bandera = true; } else { MessageBox.Show("Error en el ingreso de los lados", "Mensaje de error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); InicializarDatos(); return; } if (bandera == true) { if (((lado1 + lado2) > lado3) & ((lado2 + lado3) > lado1) & ((lado1 + lado3) > lado2)) { perimetro = PerimetroTriangulo(); area = AreaTriangulo(); txtArea.Text = area.ToString(); txtPerimetro.Text = perimetro.ToString(); } else { MessageBox.Show("El triangulo no existe", "Mensaje de Error", MessageBoxButtons.OK, MessageBoxIcon.Error); InicializarDatos(); return;

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 21

Cuaderno de Computacin II 2010


} } } private void btnResetear_Click(object sender, EventArgs e) { InicializarDatos(); } private void frmTriangulo_Load(object sender, EventArgs e) { InicializarDatos(); } private void btnSalir_Click(object sender, EventArgs e) { Close(); } } }

MENU PRINCIPAL

CIRCULO

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 22

Cuaderno de Computacin II 2010

CUADRADO

RECTANGULO

TRIANGULO

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 23

Cuaderno de Computacin II 2010


PROGRAMA QUE CALCULA DIFERENTES SERIES CON LA AYUDA DE UN MEN.
Factorial de un nmero Serie del seno(x) Serie del coseno(x) Serie de la tangente(x)

DISEO DEL MEN:

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 24

Cuaderno de Computacin II 2010


CODIGO FUENTE Y SALIDA DEL PROGRAMA

MEN:

using using using using using using using

System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Text; System.Windows.Forms;

namespace WinFormsAppSeries { public partial class frmMenu : Form { public frmMenu() { InitializeComponent(); } private void bntFactorial_Click(object sender, EventArgs e) { frmNumero Obj = new frmNumero(); Obj.Show(); } private void btnSeno_Click(object sender, EventArgs e) { frmSeno Obj = new frmSeno(); Obj.Show(); } private void bntCoseno_Click(object sender, EventArgs e) { frmCoseno Obj = new frmCoseno(); Obj.Show(); } private void bntSalir_Click(object sender, EventArgs e) { Close(); } private void frmMenu_Load(object sender, EventArgs e) { }

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 25

Cuaderno de Computacin II 2010


} }

FACTORIAL DE UN NMERO:
using using using using using using using System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Text; System.Windows.Forms;

namespace WinFormsAppSeries { public partial class frmNumero : Form { private long n; public frmNumero() { InitializeComponent(); } private void InicializarDatos() { txtNum.Text = " 0"; txtFactorial.Text = "0"; lstFactoriales.Items.Clear(); } /*private long FactorialNumero() { long j, acum = 1; for (j = 1; j <= n; j++) acum = acum * j; // acum * = j; return acum; } private long FactorialNumero(long m) { long j, acum = 1;

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 26

Cuaderno de Computacin II 2010


for (j = 1; j <= m; j++) acum = acum * j; // acum * = j; return acum; }*/ private long FactorialNumero(long n) { long respuesta; if (n == 0) respuesta = 1; else respuesta = n * FactorialNumero(n - 1); return (respuesta); } private void btnSalir_Click(object sender, EventArgs e) { Close(); } private void frmNumero_Load(object sender, EventArgs e) { InicializarDatos(); } private void btnCalcular_Click(object sender, EventArgs e) { long i, fact; string dato; try { n = long.Parse(txtNum.Text); } catch (Exception caugnt) { MessageBox.Show("Error en el ingreso de datos....." + caugnt, "mensaje de error ", MessageBoxButtons.OK, MessageBoxIcon.Error); InicializarDatos(); return;//sale del evento click } if (n >= 0) { fact = FactorialNumero(n); txtFactorial.Text = fact.ToString(); for (i = 0; i <= n; i++) { fact = FactorialNumero(i); dato = i.ToString() + "! = " + fact.ToString(); lstFactoriales.Items.Add(dato);//automaticamente da el enter } }

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 27

Cuaderno de Computacin II 2010


else { MessageBox.Show("Error en el ingreso de n...", "Mensaje de error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); InicializarDatos(); return; } } private void btnResetear_Click(object sender, EventArgs e) { InicializarDatos(); } } }

SERIE DEL SENO(X):

using using using using using using using

System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Text; System.Windows.Forms;

namespace WinFormsAppSeries { public partial class frmSeno : Form {

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 28

Cuaderno de Computacin II 2010


private long n; private float x; public frmSeno() { InitializeComponent(); } private void InicializarDatos() { txtNumero.Text = "0"; txtX.Text = "0.0"; txtSerie.Text = "0.0"; lstSeries.Items.Clear(); } private long FactorialNumero(long m) { long j, acum = 1; for (j = 1; j <= m; j++) acum = acum * j; // acum * = j; return acum; } private float SerieSeno() { long i; float acum = 0; for (i = 1; i <= n; i++) { acum = acum + ((float)Math.Pow(-1, (i + 1)) * (float)Math.Pow(x, (2 * i - 1))) / FactorialNumero(2 * i - 1); } return acum; } private void btnCalcular_Click(object sender, EventArgs e) { float serie; n = long.Parse(txtNumero.Text); x = float.Parse(txtX.Text); serie = SerieSeno(); txtSerie.Text = serie.ToString(); } private void btnResetear_Click(object sender, EventArgs e) { InicializarDatos(); } private void btnSalir_Click(object sender, EventArgs e) { Close(); } private void frmSeno_Load(object sender, EventArgs e) { InicializarDatos();

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 29

Cuaderno de Computacin II 2010


} } }

NOTA: La caja de texto solo almacena cadenas de caracteres.

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 30

Cuaderno de Computacin II 2010


4.4 FUNCIONES RECURSIVAS Una funcin que se llama a s misma se dice que es recursiva.

Una funcin f1 es recursiva si esta llama a una funcin f2, la cual bajo ciertas circunstancias llama a f1, creando un ciclo en la secuencia de llamadas. Los problemas que tienen a s mismos a tener una solucin recursiva tienen las siguientes caractersticas. a) Uno o ms casos simples del problema tienen una solucin fija no recursiva. b) Los otros casos pueden ser redefinidos en trminos de problemas que estn relacionados con los casos simples c) Al aplicar este proceso de redefinicin cada vez que la funcin recursiva es llamada, eventualmente el problema se reduce enteramente a casos simples, los cuales son relativamente fciles de resolver

Los algoritmos recursivos que se desarrollan generalmente consisten de una sentencia if con la siguiente forma en pseudocdigo: Si este es un caso simple Resolverlo Caso contrario Redefinir el problema utilizando recursin

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 31

Cuaderno de Computacin II 2010


Problema: Calcular el factorial de un nmero utilizando recursividad a) Si 0! es 1 b) n! = n*(n-1)!, para n>0 As -> Formula general o el paso recursivo

Solucin Iterativa private long Factorial (long n) { long i, acum=1; for(i=1;i<=n;i++) acum=acum*i; return(acum) } Soluci Recursiva private long Factorial (long n) { long respuesta; If (n==0) respuesta=1; else respuesta=n*factorial(n-1); return(respuesta); }

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 32

Cuaderno de Computacin II 2010

Traza de la Funcion Factorial()

fact =Factorial(3)

n es 3 3==0 es falso respuesta es 3 * Factorial(2) retun(respuesta)

n es 2 2==0 es falso respuesta es 2 * Factorial(1) retun(respuesta)

n es 1 1==0 es falso respuesta es 1 * Factorial(0) retun(respuesta)

n es 0 0==0 es Verdadero respuesta es 1 retun(respuesta)

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 33

Cuaderno de Computacin II 2010

4.5

Utilizacin De La Pila (Stack) De La Memoria

Las funciones recursivas utilizan para almacenar y retornar sus valores la pila de la memoria. El compilador mantiene en el sistema una simple pila y cada vez que ocurre una llamada a una funcin todos estos parmetros y variables locales son colocados dentro de la pila a lo largo de las direcciones de memoria de las sentencias de llamada para luego ser vaciada la pila, dependiendo de los casos que tenga un problema.

Problema: Multiplicar dos nmeros utilizando recursividad

Soluci Recursiva private int Multiplicar(int m, int n) { int respuesta; if (n!=0) { if(n==1) respuesta = m; else respuesta = m*Multiplicar(m, n-1); return(respuesta); } else return(0); }

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 34

Cuaderno de Computacin II 2010

Traza de la Funcin Multiplicar()

resp=Multiplicar(6,3) m es 6 n es 3 3==1 es falso respuesta es 6 + Multiplicar(6,2) retun(respuesta) m es 6 n es 2 2==1 es falso respuesta es 6 + Multiplicar(6,1) retun(respuesta)

18

12

m es 6 n es 1 1==1 es Verdadero respuesta es 6 retun(respuesta)

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 35

Cuaderno de Computacin II 2010


4.5.1 EJEMPLOS:

PROGRAMA QUE MULTIPLICA DOS NUMEROS MEDIANTE UNA FUNCION RECURSIVA.

using using using using using using using

CODIGO FUENTE Y SALIDA DEL PROGRAMA


System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Text; System.Windows.Forms;

namespace MultiplicacionRecursividad { public partial class Form1 : Form { private double num1, num2; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { InicializarDatos(); } private void InicializarDatos() { txtNum1.Text = "0.0"; txtNum2.Text = "0.0"; txtProducto.Text = "0.0"; } private double Multiplicacion(double n) { double acum; if (n == 0) acum = 0; else acum = num1 + Multiplicacion(n - 1); return (acum); } private void btnCalcular_Click(object sender, EventArgs e) { double producto; try { num1 = double.Parse(txtNum1.Text); num2 = double.Parse(txtNum2.Text); } catch (Exception caught) {

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 36

Cuaderno de Computacin II 2010


MessageBox.Show("Error Ingreso de datos" +caught, "Mensaje de Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation); } producto = Multiplicacion(num2); txtProducto.Text = producto.ToString(); } private void btnResetear_Click(object sender, EventArgs e) { InicializarDatos(); } private void btnSalir_Click(object sender, EventArgs e) { Close(); } } }

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 37

Cuaderno de Computacin II 2010


PROGRAMA QUE CALCULA EL FACTORIAL DE UN NMERO.
CODIGO FUENTE Y SALIDA DEL PROGRAMA

using System; using using using using using using System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Text; System.Windows.Forms;

namespace WinFormsAppSeries { public partial class frmNumero : Form { private long n; public frmNumero() { InitializeComponent(); } private void InicializarDatos() { txtNum.Text = " 0"; txtFactorial.Text = "0"; lstFactoriales.Items.Clear(); } /*private long FactorialNumero() { long j, acum = 1; for (j = 1; j <= n; j++) acum = acum * j; // acum * = j; return acum; } private long FactorialNumero(long m) { long j, acum = 1; for (j = 1; j <= m; j++) acum = acum * j; // acum * = j; return acum; }*/ private long FactorialNumero(long n) { long respuesta; if (n == 0) respuesta = 1; else respuesta = n * FactorialNumero(n - 1); return (respuesta); }

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 38

Cuaderno de Computacin II 2010


private void btnSalir_Click(object sender, EventArgs e) { Close(); } private void frmNumero_Load(object sender, EventArgs e) { InicializarDatos(); } private void btnCalcular_Click(object sender, EventArgs e) { long i, fact; string dato; try { n = long.Parse(txtNum.Text); } catch (Exception caugnt) { MessageBox.Show("Error en el ingreso de datos....." + caugnt, "mensaje de error ", MessageBoxButtons.OK, MessageBoxIcon.Error); InicializarDatos(); return;//sale del evento click } if (n >= 0) { fact = FactorialNumero(n); txtFactorial.Text = fact.ToString(); for (i = 0; i <= n; i++) { fact = FactorialNumero(i); dato = i.ToString() + "! = " + fact.ToString(); lstFactoriales.Items.Add(dato);//automaticamente da el enter } } else { MessageBox.Show("Error en el ingreso de n...", "Mensaje de error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); InicializarDatos(); return; } } private void btnResetear_Click(object sender, EventArgs e) { InicializarDatos();

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 39

Cuaderno de Computacin II 2010


} } }

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 40

Cuaderno de Computacin II 2010


4.6 MANEJO DE ARREGLOS.

FUNCIN PARA GENERAR ARREGLOS ALEATORIOS

Prvate void GenerarArregloAleatorio(ref int[]v, ref int num) { int []temp=new int[MAX]; Random randOnj=new Random(MAX); for(int i=0; i<MAX; i++) temp[i]=randObj.Next(0,16); num=MAX; CopiarDatosArreglo(temp, MAX, ref v, ref num); }
4.6.1 Ejemplos:

PROGRAMA PARA REALIZAR LAS OPERACIONES ENTRE CONJUNTOS.


using using using using using using using System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Text; System.Windows.Forms;

namespace WinAppManejoArreglos { public partial class Arreglos : Form { //Datos private const int MAX = 16; private int[] A = new int[MAX]; private int[] B = new int[MAX]; private int[] C = new int[MAX]; private int num_A = 0, num_B = 0, num_C = 0; public Arreglos() { InitializeComponent(); }

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 41

Cuaderno de Computacin II 2010


private void InicializarDatos() { InicializarArreglo(ref A, ref num_A); InicializarArreglo(ref B, ref num_B); InicializarArreglo(ref C, ref num_C); txtElementoA.Text = ""; txtElementoB.Text = ""; lstElementoA.Items.Clear(); lstElementoB.Items.Clear(); lstElementoC.Items.Clear(); } //Funciones miembro (metodos) private bool InsertarDatoArreglo(ref int[] v, ref int num, int dato) { for (int i = 0; i < num; i++) { if (v[i] == dato) return false; } if (num < MAX) { v[num] = dato; num++; return true; } else return false; } private void InicializarArreglo(ref int [] v, ref int num) { for (int i=0;i<MAX;i++) v[i]=0; num=0; } private void UnionConjuntos() { InicializarArreglo(ref C, ref num_C); CopiarDatosArreglo(A, num_A, ref C, ref num_C); for (int i = 0; i < num_B; i++) { InsertarDatoArreglo(ref C, ref num_C, B[i]); } } private void InterseccionConjuntos() { InicializarArreglo(ref C, ref num_C); for (int i = 0; i < num_A; i++) { for (int j = 0; j < num_B; j++) { if (A[i]==B[j]) { InsertarDatoArreglo(ref C,ref num_C,A[i]); break;

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 42

Cuaderno de Computacin II 2010


} } } } private void DiferenciaConjuntos(ref int []v, ref int num) { InicializarArreglo(ref C, ref num_C); for (int i = 0; i < num_A; i++) { for (int j = 0; j < num_B; j++) { if (A[i] == B[j]) { A[i] = -1; } } if (A[i] != -1) { InsertarDatoArreglo(ref C, ref num_C, A[i]); } } } private void DiferenciaConjuntos2(ref int[] v, ref int num) { int[] Temp = new int[MAX]; InicializarArreglo(ref C, ref num_C); for (int i = 0; i < num_B; i++) { for (int j = 0; j < num_A; j++) { if (B[i] == A[j]) { B[i] = -1; } } if (B[i] != -1) { InsertarDatoArreglo(ref C, ref num_C, B[i]); } } } private void ImprimirArreglo(ref ListBox lstElemento, int[] v,int num) { for (int i = 0; i < num; i++) { lstElemento.Items.Add(v[i].ToString()); } } private void Form1_Load(object sender, EventArgs e) { InicializarDatos();

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 43

Cuaderno de Computacin II 2010


} private void btnInsertarA_Click(object sender, EventArgs e) { lstElementoA.Items.Clear(); InsertarDatoArreglo(ref A, ref num_A, int.Parse(txtElementoA.Text)); txtElementoA.Text=""; txtElementoA.Focus(); ImprimirArreglo(ref lstElementoA,A,num_A); } private void btnInsertarB_Click(object sender, EventArgs e) { lstElementoB.Items.Clear(); InsertarDatoArreglo(ref B, ref num_B, int.Parse(txtElementoB.Text)); txtElementoB.Text = ""; txtElementoB.Focus(); ImprimirArreglo(ref lstElementoB, B, num_B); } private void CopiarDatosArreglo(int[] origen, int num_o, ref int[] destino, ref int num_d) { num_d = num_o; for (int i = 0; i < num_o; i++) destino[i] = origen[i]; } private void InvertirArreglo(ref int[] v, int num) { int[] Temp = new int[MAX]; int i, j, num_temp=num; for (i = 0, j = num - 1; i < num; i++, j--) Temp[j] = v[i]; CopiarDatosArreglo(Temp, num_temp, ref v, ref num); } private void OrdenarDatos(ref int[] v, int num) { int actual, sig, temp; for(actual=0;actual<num;actual++) { for (sig=actual+1;sig<num;sig++) { if(v[actual]>v[sig]) { temp = v[actual]; v[actual] = v[sig]; v[sig] = temp; } } } } private void btnInvertirA_Click(object sender, EventArgs e) { lstElementoA.Items.Clear();

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 44

Cuaderno de Computacin II 2010


InvertirArreglo(ref A, num_A); ImprimirArreglo(ref lstElementoA, A, num_A); } private void btnOrdenarA_Click(object sender, EventArgs e) { lstElementoA.Items.Clear(); OrdenarDatos(ref A, num_A); ImprimirArreglo(ref lstElementoA, A, num_A); } private void btnIvertirB_Click(object sender, EventArgs e) { lstElementoB.Items.Clear(); InvertirArreglo(ref B, num_B); ImprimirArreglo(ref lstElementoB, B, num_B); } private void btnOrdenarB_Click(object sender, EventArgs e) { lstElementoB.Items.Clear(); OrdenarDatos(ref B, num_B); ImprimirArreglo(ref lstElementoB, B, num_B); } private void btnResetear_Click(object sender, EventArgs e) { InicializarDatos(); } private void btnSalir_Click(object sender, EventArgs e) { Close(); } private void btnUnion_Click(object sender, EventArgs e) { lstElementoC.Items.Clear(); UnionConjuntos(); ImprimirArreglo(ref lstElementoC, C, num_C); } private void btnInterseccion_Click(object sender, EventArgs e) { lstElementoC.Items.Clear(); InterseccionConjuntos(); ImprimirArreglo(ref lstElementoC, C, num_C); } private void btnInvertirC_Click(object sender, EventArgs e) { lstElementoC.Items.Clear(); InvertirArreglo(ref C, num_C); ImprimirArreglo(ref lstElementoC, C, num_C);

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 45

Cuaderno de Computacin II 2010


} private void btnOrdenarC_Click(object sender, EventArgs e) { lstElementoC.Items.Clear(); OrdenarDatos(ref C, num_C); ImprimirArreglo(ref lstElementoC, C, num_C); } private void btnDiferencia_Click(object sender, EventArgs e) { lstElementoC.Items.Clear(); DiferenciaConjuntos(ref C, ref num_C); ImprimirArreglo(ref lstElementoC, C, num_C); } private void btnDiferencia2_Click(object sender, EventArgs e) { lstElementoC.Items.Clear(); DiferenciaConjuntos2(ref C, ref num_C); ImprimirArreglo(ref lstElementoC, C, num_C); } } }

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 46

Cuaderno de Computacin II 2010

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 47

Cuaderno de Computacin II 2010


4.7 Grficos con GDI

Microsoft.Net define una librera para manejar grficos denominada GDI.+(Graphical Device Interface COM+) con las siguientes clases: System.Drawing System.Drawing. Drawing 2D System.Drawing. Imaging System.Drawing. Printing System.Drawing. Design System.Drawing. Text

Picture Box(pic.grafico)

x(+) (0,0) (320,0) (640,0)

y(+)

(0,240)

(320,240)

(640,240)

(0,480)

(320,480)

(640,480)

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 48

Cuaderno de Computacin II 2010


WinAppFuncinCuadrtica GDI + -> 20
4.7.1 Ejemplo:

PROGRAMA QUE CALCULA LAS RACES DE UNA ECUACIN CUADRATICA Y GRAFICA DICHA ECUACIN.

using using using using using using using

CODIGO FUENTE Y SALIDA DEL PROGRAMA


System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Text; System.Windows.Forms;

namespace WinAppFuncionCuadratica { public partial class frmFuncionCuadratica : Form { //Declaracion de variables private float a, b, c; private float x1, x2; private int bandera = 0; private const float FE = 10; private void InicializarDatos() { txtA.Text = "0"; TxtB.Text = "0"; txtC.Text = "0"; txtX1.Text = "0"; txtX2.Text = "0"; lstTablaValores.Items.Clear(); picGrafico.Refresh(); a = 0; b = 0; c = 0; x1 = 0; x2 = 0; bandera=0; } public frmFuncionCuadratica() { InitializeComponent();

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 49

Cuaderno de Computacin II 2010


} private void LeerDatos() { try { a = float.Parse(txtA.Text); b = float.Parse(TxtB.Text); c = float.Parse(txtC.Text); } catch (Exception caught) { MessageBox.Show("Error en el ingreso de los datos...." + caught, "Mensaje de Error", MessageBoxButtons.OK, MessageBoxIcon.Error); InicializarDatos(); return; } } private float Discriminante(float a, float b, float c) { return (b * b - 4 * a * c); } private void CalcularRaices() { float D; if (a == 0) { if (c == 0) { MessageBox.Show("La raiz es cero", "Raices de la funcion", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } else { float x = -c / b; MessageBox.Show("Una unica solucion para X=" + x.ToString(), "Raices de la funcion", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } } else

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 50

Cuaderno de Computacin II 2010


{ D = Discriminante(a, b, c); if (D > 0) { MessageBox.Show("Las raices son reales", "Raices de la funcion", MessageBoxButtons.OK, MessageBoxIcon.Information); x1=(-b+(float)Math.Sqrt(D))/(2*a); x2=(-b-(float)Math.Sqrt(D))/(2*a); bandera = 1; } if (D == 0) { MessageBox.Show("Existe una sola raiz real", "Raices de la funcion", MessageBoxButtons.OK, MessageBoxIcon.Information); x1 = -b / (2 * a); x2 = -b / (2 * a); bandera = 2; } if (D < 0) { MessageBox.Show("Las raices son imaginarias", "Raices de la funcion", MessageBoxButtons.OK, MessageBoxIcon.Information); x1 = -b / (2 * a); x2 = (float)Math.Sqrt((float)Math.Abs(D)) / (2 * a); bandera = 3; } } } private void ImprimirRaices() { if (bandera == 1) { txtX1.Text = x1.ToString(); txtX2.Text = x2.ToString(); } if (bandera == 2) { txtX1.Text = x1.ToString() + " = " + x2.ToString(); txtX2.Text = x2.ToString() + " = " + x1.ToString(); }

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 51

Cuaderno de Computacin II 2010


if (bandera == 3) { txtX1.Text = "(" + x1.ToString() + " + " + x2.ToString() + "i)"; txtX2.Text = "(" + x2.ToString() + " - " + x1.ToString() + "i)"; } } private float f(float x) { return (a * x * x + b * x + c); } private void GraficarFuncion(PointF[] P) { float xp, yp; for (int x = -10; x <= 10; x++) { xp = 320 + x * FE; yp = 240 + -1 * f(x) * FE; P[x + 10] = new PointF(xp,yp); lstTablaValores.Items.Add(xp.ToString()+ " , "+ yp.ToString()); } } private void frmFuncionCuadratica_Load(object sender, EventArgs e) { InicializarDatos(); } private void btnResetear_Click(object sender, EventArgs e) { InicializarDatos(); } private void btnSalir_Click(object sender, EventArgs e) { Close(); } private void btnCalcular_Click(object sender, EventArgs e) { LeerDatos(); CalcularRaices(); ImprimirRaices(); } private void btnGraficar_Click(object sender, EventArgs e) { Graphics G; G = picGrafico.CreateGraphics(); Pen Pluma = new Pen(Color.Red);

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 52

Cuaderno de Computacin II 2010


G.DrawLine(Pluma, 0,240,640,240); G.DrawLine(Pluma, 320, 0, 320, 480); Pluma = new Pen(Color.Blue); PointF[] P = new PointF[21]; GraficarFuncion(P); G.DrawCurve(Pluma, P); } } }

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 53

Cuaderno de Computacin II 2010


4.8 GLOSARIO.

Evento: Accin que ejecuta un objeto Using: Equivalente al # include Sender: Parmetro que activa el manejador de eventos de los objetos E: Parmetro que activa el modo grfico (Graficador objetos) Show: muestra mensaje new:Construimos objeto, separamos memoria. Parse: esta en frances y significa pasar, convetir.

Autor: Fanny Alquinga-Alejandra Fonseca.

Pgina 54

Вам также может понравиться