viernes, 31 de agosto de 2012

algoritmo para guardar un archivo


// Este ejemplo muestra cómo se procesa el contenido de un archivo, que
//indica operaciones matemáticas básicas: * / + -
// Este ejemplo en particular, escribe el resultado en un archivo destino
using System;
using System.IO;
class Calculadora
{
    StreamReader sr;
    StreamWriter sw;
    bool abierto1 = false;
    bool abierto2 = false;
    // Constructor: Recibe el nombre del archivo y lo intenta abrir.
    // Si no puede abrirse para lectura, "abierto" queda como false
    // Si lo puede abrir, crea un segundo archivo con un nombre similar.
    public Calculadora(string filename)
    {
        try
        {
            sr = new StreamReader(filename);
            abierto1 = true;
        }
        catch (Exception e)
        {
            Console.WriteLine("Error en la apertura de \"{0}\": {1}",
            filename, e.ToString());
        }
        if (abierto1)
        {
            string nombrearchivo2;
           
            nombrearchivo2 = "c.txt";
            try
            {
                sw = new StreamWriter(nombrearchivo2);
                abierto2 = true;
            }
            catch (Exception e)
            {
                Console.WriteLine("Error en la apertura de \"{0}\": {1}",
                nombrearchivo2, e.ToString());
            }
        }
    }
    // Operacion: Recibe la operación y dos números en forma de string.
    // Retorna el resultado (int) de la operación entre ambos números.
    int Operacion(string op, string n1, string n2)
    {
        switch (op)
        {
            case "+": return (int.Parse(n1) + int.Parse(n2));
            case "-": return (int.Parse(n1) - int.Parse(n2));
            case "*": return (int.Parse(n1) * int.Parse(n2));
            case "/": return (int.Parse(n1) / int.Parse(n2));
        }
        return (0);
    }
    // Procesar: lee el archivo abierto, línea por línea,
    // procesando el contenido en forma de operaciones y escribiendo
    // el resultado en un segundo archivo.
    // Observaciones: Al finalizar se cierran los dos streams.
    // No se valida el formato de c/línea.
    public void Procesar()
    {
        string linea, linea2;
        string[] elementos;
        // Si no se pudo abrir, no se podrá leer ni escribir
        if (!abierto1 || !abierto2) return;
        Console.WriteLine("Procesando ...");
        linea = sr.ReadLine();
        while (linea != null)
        {
            elementos = linea.Split();
            // ahora graba los resultados en el segundo archivo
            linea2 = linea + " = " +
            Operacion(elementos[1], elementos[0], elementos[2]).ToString();
            sw.WriteLine(linea2);
            linea = sr.ReadLine();
        }
        sr.Close(); abierto1 = false;
        sw.Close(); abierto2 = false;
        Console.WriteLine("Listo");
    }

    static void Main(string[] args)
    {
        string nombre;
        Console.Write("Nombre del archivo: ");
        nombre = Console.ReadLine();
        Calculadora c = new Calculadora(nombre);
        c.Procesar();
        Console.ReadLine();
    }
}

lunes, 27 de agosto de 2012

Metodo ordenacion shell

        //Metodo de Ordenacion SHELL
        private void button5_Click(object sender, EventArgs e)
        {
            int i, j, inc, temp;
            int n = 10;

            for (inc = 1; inc < n; inc = (inc * 3) + 1) ;

            while (inc > 0)
            {
                for (i = inc; i < n; i++)
                {
                    j = i;
                    temp = A[i];
                    while ((j >= inc) && (A[j - inc] > temp))
                    {
                        A[j] = A[j - inc];
                        j = j - inc;
                    }
                    A[j] = temp;
                }
                inc /= 2;
            }

        }

viernes, 24 de agosto de 2012

manejo de archivos ejemplo de como traer un archivo


using System;
using System.IO;

class EJ_Archivo
{
    static void Main()
    {
    string fileName = @"C:\Documents and Settings\usuario\Escritorio\algoritmos2\paulo.txt";
    FileStream stream = new FileStream(fileName, FileMode.Open,
    FileAccess.Read);
    StreamReader reader = new StreamReader(stream);
    while (reader.Peek() > -1) Console.WriteLine(reader.ReadLine());
    reader.Close();
    Console.Read();
    }
}

multiplicacion de matrices en c#

algoritmo implementado en c sharp que multiplica 2 matrices
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
    class Program
    {
        static void Main(string[] args)
        {
            int respuesta = 0;
            Console.WriteLine("cantidad de reglones");
            int r = int.Parse(Console.ReadLine());
            Console.WriteLine("cantidad de columnas");
            int c = int.Parse(Console.ReadLine());
            int[,] matriz1 = new int[r, c];
            Console.WriteLine("cantidad de reglones de la matriz a multiplicar");
            int r2 = int.Parse(Console.ReadLine());
            Console.WriteLine("cantidad de columnas de la matriz a multiplicar");
            int c2 = int.Parse(Console.ReadLine());
            int[,] matriz2 = new int[r2, c2];

            //si el numero de filas de la 1 es igual al numero de columnas de la 2 entonces
            //creamos una matriz de respuestas con su respectivo tamano
            //de lo contrario mostramos un error por pantalla

            if (c == r2)
            {
                int[,] matrizRespuestas = new int[r, c2];//CREAMOS LA MATRIZ RESULTADO

                // COMIENZA CICLO PARA LLENAR LA PRIMERA MATRIZ
                for (int i = 0; i < r; i++)
                {
                    for (int j = 0; j < c; j++)
                    {
                        Console.WriteLine("matriz 1 ingrese un valor en la posicion :{0},{1} ", i, j);
                        matriz1[i, j] = int.Parse(Console.ReadLine());

                    }
                }
                //COMIENZA CICLO PARA LLENAR LA SEGUNDA MATRIZ
                Console.WriteLine("LISTO!! AHORA INGRESE LOS VALORES DE LA SEGUNDA MATRIZ");
                for (int i = 0; i < r2; i++)
                {
                    for (int j = 0; j < c2; j++)
                    {
                        Console.WriteLine("matriz 2 ingrese un valor en la posicion :{0},{1} ", i, j);
                        matriz2[i, j] = int.Parse(Console.ReadLine());

                    }
                }
                // FIN PARA LLENAR LAS DOS MATRICES
                // AHORA VAMOS A MULTIPLICARLAS
                //PARA ELLO PRIMERO TENEMOS QUE MILTIPLICAR Y SUMAR VECTORES
                for (int i = 0; i < r; i++)
                {
                    for (int j = 0; j < c2; j++)
                    {
                        for (int k = 0; k < c; k++)
                        {
                            respuesta += matriz1[i, k] * matriz2[k, j];
                        }
                        matrizRespuestas[i, j] = respuesta;
                        respuesta = 0;
                    }

                }
                Console.WriteLine("!!!!!!LA RESPUESTA ES !!!!!!");
                string igual = "";
                for (int i = 0; i < r; i++)
                {
                    for (int j = 0; j < c2; j++)
                    {
                        igual = igual + (matrizRespuestas[i, j].ToString());
                    }
                    Console.WriteLine("[" + igual + "]\n");
                    igual = "";

                }
                Console.Read();




            }
            else
            {
                Console.WriteLine("!!!!!!!!!!!no se puede multiplicar estas matrices !!!!!");
                Console.Read();
            }

        }
    }
}

jueves, 23 de agosto de 2012

Triangulo de pascal en c sharp c#


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 WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

        }
        int[,] A;
        //creamos un boton y dos textbox
        //un textbox para ingresar el coeficiente de la x
        // otro para mostrar la matriz 
        //fijate bien que este activado 
        //el multiline en donde vas a mostrar la matriz

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                int filas = int.Parse(textBox1.Text);
                int columnas = filas + 1;
                A=new int[filas,columnas];
                for (int i = 0; i < filas; i++)
                {
                        A[i, 0] = 1;
                }
                for (int i = 1; i < filas; i++)
                {
                 
                        A[i, i+1] = 1;
                 
                }

/////////////comienza a llenar el triangulo de pascal
                if (filas >= 2)
                {
                    A[1, 1] = 2;
                    for (int i = 2; i < filas; i++)
                    {
                        for (int j = 1; j < columnas; j++)
                        {
                            if (A[i, j] != 1) // esta condicion es para asegurarnos que no se pase
                            {
                                A[i, j] = A[i - 1, j - 1] + A[i - 1, j];
                            }
                        }

                    }
                }
                else
                {
                    textBox2.Text = "debe de ingresar un dato positivo mayor a 1";
                }
            //aca imprimimos la matriz terminada
                for (int i = 0; i < filas; i++)
                {
                    textBox2.Text += " [";
                    for (int j = 0; j < columnas; j++)
                    {
                        textBox2.Text = textBox2.Text + " " + A[i, j];
                    }
                    textBox2.Text += " ] \r\n";
                }
            }
            catch (Exception)
            {
                MessageBox.Show("no valido");
            }
        }
    }
}


/// aunque se ve sencillo la lógica de este  algoritmos es muy interesante

viernes, 17 de agosto de 2012

busqueda binaria en c sharp


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 WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int[] vector = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
            int longitud = vector.Length;
            int datoabuscar = int.Parse(textBox1.Text);          
            int posicion = buscador(vector, datoabuscar);
            if (vector[posicion] == datoabuscar)
                MessageBox.Show("el dato esta en la posicion" + posicion);
            else
                MessageBox.Show("dato no encontrado");
           

        }
        static public int buscador(int[] vec, int dato)
        {
            int limiteSuperior = vec.Length -1;
            int LimiteInferior = 0;
            int medio;
            while (LimiteInferior < limiteSuperior)
            {
               medio = (LimiteInferior + limiteSuperior)/2;
               if (vec[medio] == dato)
               {

                   return (medio);
                 
               }
               else if (vec[medio] > dato)
               {
                   limiteSuperior = medio - 1;
               }
               else
                   LimiteInferior = medio + 1;


             }
            return -1;

        }
    }
}

temas algoritmos 2 clase 10

estudiar busqueda secuencial,
estudiar busqueda binaria
ordenacion por seleccion, inserccion,binaria,shell
multiplicacion de matrices

definicion de matrices en c sharp

int [,] nombrevariable = new in [3,3]  // 3,3 es la dimencion de la matriz

jueves, 16 de agosto de 2012

tablas de distribucion de frecuencias en python

este programa ayuda a  hacerte el trabajo de distribucion de frecuencias mas facil
solo llevalo a c sharp.
from math import*
#tabla de distribucion de frecuencias
print("***********TABLA DE DISTRIBUCION DE FRECUENCIAS**************")
#obtenemos el tamaño del vector
tama = int(input("digite la cantidad de datos que va a ingresar"))
datos = [0]*tama #creamos el vector de la cantidad que tiene la variable tama
i= 0
print ("ingrese sus datos")
while i < tama:
    datos[i]=int (input ("dato: "))
    i+=1
#comienza metodo de ordenacion por seleccion
i=0
while i < tama:
    mayor= i
    j=i+1
    y=0
    while j < tama:
        if datos[mayor]<datos[j]:
            mayor = j
        j+=1
    aux = datos[mayor]
    datos[mayor]=datos[i]
    datos[i]=aux
    i+=1
 
print("estos son sus datos ordenados decendentemente")
print(datos)
m = ceil(1 + 3.3*log10(tama))
r = datos[0]-datos[tama-1]
a= ceil(r/m)-0.1
print("------------------------------------------")
print("------------------------------------------")
print("---------------Respuestas-----------------")


print("m = ",m," R= ",r," A = ",a)


 



 

Tablas de correlacion de estadistica en python


#tablas de correlacion
print("----------------TABLAS DE CORRELACIÓN-------------------------")
#obtenemos el tamaño del vector
tama = int(input("digite la cantidad de datos que va a ingresar"))
datos = [0]*tama #creamos el vector de la cantidad que tiene la variable tama
datos2 = [0]*tama
i= 0
SumatoriaX2=0
SumatoriaY2=0
SumatoriaY=0
SumatoriaX=0

sx2=0#sumatoria de x - xpromedio todo al cuadrado
sy2=0
sxy=0
#terminamos de definir algunas variables
############################################################

print ("ingrese datos de x para hallar correlacion")
while i < tama:
    datos[i]=float (input ("dato: "))
    SumatoriaX += datos[i] #sumamos todos los x
    SumatoriaX2+=(datos[i]**2)
    i+=1
print ("LOS DATOS INGRESADOS SON ",datos)

##########################################################

print ("ingrese datos de y ")
print ("ingrese sus datos")
Xpromedio= SumatoriaX/tama
i =0
while i < tama:
    datos2[i]=float (input ("dato: "))
    SumatoriaY+=datos2[i]
    SumatoriaY2+=(datos[i]**2)
    i+=1
Ypromedio= SumatoriaY/tama
i=0
print("-----------------------------------------------------------------------------------------------")


while i < tama:
    print("--------intervalo ",i,"----------------------------------------------------------------")
    print("|x| ",datos[i])
    print("|y| ",datos2[i])
    print("|X*Y| ",datos[i]*datos2[i])
    print("|Xª2| ",datos[i]**2)
    print("|Yª2| ",datos2[i]**2)
    print("|x -X|",datos[i]-Xpromedio)
    print("|y-Y|",datos2[i]-Ypromedio)
    print("|x -X|ª2",(datos[i]-Xpromedio)**2)
    print("|y-Y|ª2",(datos2[i]-Ypromedio)**2)
    sx2+= (datos[i]-Xpromedio)**2
    sy2+= (datos2[i]-Ypromedio)**2
    sxy += datos[i]*datos2[i]  
    i+=1
print("-----------------------------------------------------------------------------------------------")
print("Fin Tabla")
print("-----------------------------------------------------------------------------------------------")
sx=(sx2/(tama-1))**(1/2)
print("sx=",sx)

#la raiz cuadrada de la sumatoria de x-xpromedio elevado al cuadrado dividido el numero de elementos
sy=(sy2/(tama-1))**(1/2)
b =((tama*sxy) - (SumatoriaX*SumatoriaY))/((tama*SumatoriaX2) - (SumatoriaX**2))
a = (SumatoriaY/tama)- (b*SumatoriaX/tama)
sxyy=(sxy/(tama))-(Xpromedio*Ypromedio)
print("sy=",sy)
print("sumatoria xy=",sxy)
print("promedio x",Xpromedio)
print("promedio y",Ypromedio)

r= sxyy/(sx*sy)
print ("la ecuacion de la linea recta es ")
print ("Y = ",a ," + ",b,"X")
print ("la correlacion es de",r,"sxy= ", sxyy)
if r>(-1) and r<=(-0.9):
    print("!!!la correlacion es Excelente!!!!")
if r>=(0.8) and r<=(0.9):
    print("!!!la correlacion es buena!!!")
if r>(0.6) and r<(0.8):
    print("!!!la correlacion es regular!!!")
if r>(0.3) and r<(0.6):
    print("!!!mala!!!")









domingo, 12 de agosto de 2012

busqueda binaria normal

    private void bbi_Click(object sender, EventArgs e)
        {
            bool sw = true;
          
            //Comienza Busqueda Binaria
            int LimiteInferior = 0;
            int LimiteSuperior = vectorOrdenado.Length;
            int Medio = (LimiteSuperior - LimiteInferior) / 2;
            for(int i = 0;i< vectorOrdenado.Length;i++)
            {
                if (vectorOrdenado[i].CompareTo(datoparabuscar.Text)<0)
                {
                    LimiteSuperior= Medio;
                    Medio = (LimiteSuperior - LimiteInferior) / 2;
                }
                if (vectorOrdenado[i].CompareTo(datoparabuscar.Text) > 0)
                {
                    LimiteInferior = Medio;
                    Medio = (LimiteSuperior - LimiteInferior) / 2;
                }
                if (vectorOrdenado[i].CompareTo(datoparabuscar.Text) == 0)
                {
                    sw = false;
                    MessageBox.Show("El dato buscado se encuentra en la posicion "+i );
                  
                }
              
                  
            }
            if (sw)
                MessageBox.Show("El dato buscado no se encuentra  ");

        }

        private void button2_Click(object sender, EventArgs e)
        {
          busquedaRecursiva(vectorOrdenado, vectorOrdenado.Length,0).ToString();

            if (!swiche)
                MessageBox.Show("no existe tal dato");

        }

algoritmo de ordenacion por seleccion en c sharp

este es un método de ordenación muy común
para ordenar vectores

int  posMayor;
                for (int cont1 = 0; cont1 < tama - 1; cont1++)
                {
                    posMayor = cont1;
                    for (cont2 = cont1 + 1; cont2 < tama; cont2++)// tama es el tamaño del vector
                    {
                        if (words[posMayor].CompareTo(words[cont2]) < 0)
                        {
                            posMayor = cont2;
                        }

                    }
                    aux = words[posMayor];
                    words[posMayor] = words[cont1];
                    words[cont1] = aux;
                }

       

           

busqueda binaria recursiva

        private int busquedaRecursiva(string[] Vec,int limisup,int liminf)
        {

           
            int limiteInferior = liminf;
            int limiteSuperior = limisup;
            int Medio = (limiteSuperior - limiteInferior) / 2;
            if (Vec[Medio].CompareTo(datoparabuscar.Text) < 0)
                  limiteSuperior = (busquedaRecursiva(Vec, Medio-1,limiteInferior));
            if (Vec[Medio].CompareTo(datoparabuscar.Text) > 0)
                limiteInferior = (busquedaRecursiva(Vec, limisup+1,Medio));
            if (Vec[Medio].CompareTo(datoparabuscar.Text) == 0)
            {
                console.WriteLine("su dato fue encontrado en la posicion" + Medio);
                swiche = true;
            }
       

ordenacion y busqueda binaria recursiva y no recursiva por paulo en c#


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 metodo_ordenacion
{
    public partial class Form1 : Form
    {
        string[] vectorOrdenado;
        bool swiche = false;

        public Form1()
        {
            InitializeComponent();
        }

        private void OrdenarButton_Click(object sender, EventArgs e)
        {
            try
            {
                string s = datos.Text;
                string[] words = s.Split(',');
                int cont1 = 0;
                int cont2 = 0;
                int posMayor;
                int tama = words.Length;
                string aux;
                //ordenador
                for (cont1 = 0; cont1 < tama - 1; cont1++)
                {
                    posMayor = cont1;
                    for (cont2 = cont1 + 1; cont2 < tama; cont2++)
                    {
                        if (words[posMayor].CompareTo(words[cont2]) < 0)//{0.5.2.3}
                        {
                            posMayor = cont2;
                        }

                    }
                    aux = words[posMayor];
                    words[posMayor] = words[cont1];
                    words[cont1] = aux;
                }
                int cont3 = 0;

                //fin ordenador

                while (cont3 < tama)
                {
                    pantalla.Items.Add(words[cont3]);
                    cont3++;
                }
                vectorOrdenado = words;
            }
            catch (Exception)
            { MessageBox.Show("ERROR","ErrorBlinkStyle"); }

        }
        //fin del boton ordenar

        private void bbi_Click(object sender, EventArgs e)
        {
            bool sw = true;
         
            //Comienza Busqueda Binaria
            int LimiteInferior = 0;
            int LimiteSuperior = vectorOrdenado.Length;
            int Medio = (LimiteSuperior - LimiteInferior) / 2;
            for(int i = 0;i< vectorOrdenado.Length;i++)
            {
                if (vectorOrdenado[i].CompareTo(datoparabuscar.Text)<0)
                {
                    LimiteSuperior= Medio;
                    Medio = (LimiteSuperior - LimiteInferior) / 2;
                }
                if (vectorOrdenado[i].CompareTo(datoparabuscar.Text) > 0)
                {
                    LimiteInferior = Medio;
                    Medio = (LimiteSuperior - LimiteInferior) / 2;
                }
                if (vectorOrdenado[i].CompareTo(datoparabuscar.Text) == 0)
                {
                    sw = false;
                    MessageBox.Show("El dato buscado se encuentra en la posicion "+i );
                 
                }
             
                 
            }
            if (sw)
                MessageBox.Show("El dato buscado no se encuentra  ");

        }

        private void button2_Click(object sender, EventArgs e)
        {
          busquedaRecursiva(vectorOrdenado, vectorOrdenado.Length,0).ToString();

            if (!swiche)
                MessageBox.Show("no existe tal dato");

        }
        private int busquedaRecursiva(string[] Vec,int limisup,int liminf)
        {

         
            int limiteInferior = liminf;
            int limiteSuperior = limisup;
            int Medio = (limiteSuperior - limiteInferior) / 2;
            if (Vec[Medio].CompareTo(datoparabuscar.Text) < 0)
                  limiteSuperior = (busquedaRecursiva(Vec, Medio-1,limiteInferior));
            if (Vec[Medio].CompareTo(datoparabuscar.Text) > 0)
                limiteInferior = (busquedaRecursiva(Vec, limisup+1,Medio));
            if (Vec[Medio].CompareTo(datoparabuscar.Text) == 0)
            {
                MessageBox.Show("su dato fue encontrado en la posicion" + Medio);
                swiche = true;
            }
     
         

            return(Medio);
             
        }




    }
nota: para realizar la busqueda binaria el vector tiene que estar ordenado.

martes, 7 de agosto de 2012

calculadora cientifica en csharp


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 WindowsFormsApplication1
{
    public partial class formaPrincipal : Form
    {
        double resultado, suma, numero1,numero2 = 0;
        bool swi = true ;
        string operador = "";
        public formaPrincipal()
        {
            InitializeComponent();
         
        }

        private void button16_Click(object sender, EventArgs e)
        {
            try
            {
                operador = "-";
                numero1 = double.Parse(cajaTexto.Text);
                swi = true;
            }
            catch (Exception)
            {
                MessageBox.Show("digite un valor valido", "error");
            }
        }

        private void label1_Click(object sender, EventArgs e)
        {
            cajaTexto.Text = "";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (swi)
            {
                cajaTexto.Text = "";
                cajaTexto.Text = "1";
                swi = false;
            }
            else
                cajaTexto.Text = cajaTexto.Text + "1";
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (swi)
            {
                cajaTexto.Text = "";
                cajaTexto.Text = "2";
                swi = false;
            }
            else
                cajaTexto.Text = cajaTexto.Text + "2";
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (swi)
            {
                cajaTexto.Text = "";
                cajaTexto.Text = "3";
                swi = false;
            }
            else
                cajaTexto.Text = cajaTexto.Text + "3";
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (swi)
            {
                cajaTexto.Text = "";
                cajaTexto.Text = "4";
                swi = false;
            }
            else
                cajaTexto.Text = cajaTexto.Text + "4";
        }

        private void button5_Click(object sender, EventArgs e)
        {
            if (swi)
            {
                cajaTexto.Text = "";
                cajaTexto.Text = "5";
                swi = false;
            }
            else
                cajaTexto.Text = cajaTexto.Text + "5";
        }

        private void button6_Click(object sender, EventArgs e)
        {
            if (swi)
            {
                cajaTexto.Text = "";
                cajaTexto.Text = "6";
                swi = false;
            }
            else
                cajaTexto.Text = cajaTexto.Text + "6";
        }

        private void button7_Click(object sender, EventArgs e)
        {
            if (swi)
            {
                cajaTexto.Text = "";
                cajaTexto.Text = "7";
                swi = false;
            }
            else
                cajaTexto.Text = cajaTexto.Text + "7";
        }

        private void button8_Click(object sender, EventArgs e)
        {
            if (swi)
            {
                cajaTexto.Text = "";
                cajaTexto.Text = "8";
                swi = false;
            }
            else
                cajaTexto.Text = cajaTexto.Text + "8";
        }

        private void button9_Click(object sender, EventArgs e)
        {
            if (swi)
            {
                cajaTexto.Text = "";
                cajaTexto.Text = "9";
                swi = false;
            }
            else
                cajaTexto.Text = cajaTexto.Text + "9";
        }

        private void button10_Click(object sender, EventArgs e)
        {
            cajaTexto.Text = cajaTexto.Text + "0";
        }

        private void button12_Click(object sender, EventArgs e)
        {
            cajaTexto.Text = "0";
            suma = 0;
            swi = true;
        }

        private void button13_Click(object sender, EventArgs e)
        {
            try
            {
             
                operador = "+";
               numero1 = double.Parse(cajaTexto.Text);
               suma = suma + numero1;
               swi = true;                  
            }
            catch(Exception)
            {
                MessageBox.Show("digite un valor valido","error");
            }
        }

        private void cajaTexto_TextChanged(object sender, EventArgs e)
        {
         
        }

        private void button15_Click(object sender, EventArgs e)
        {
            try
            {
                operador = "*";
                numero1 = double.Parse(cajaTexto.Text);
                if (suma != 0)
                    suma = suma * numero1;

             
                 
                swi = true;
            }
            catch (Exception)
            {
                MessageBox.Show("digite un valor valido", "error");
            }
        }

        private void button14_Click(object sender, EventArgs e)
        {
            try
            {
                operador = "/";
                numero1 = double.Parse(cajaTexto.Text);
                swi = true;
            }
            catch (Exception)
            {
                MessageBox.Show("digite un valor valido", "error");
            }
        }

        private void button28_Click(object sender, EventArgs e)
        {
            try
            {
                if (cajaTexto.Text != "")
                    numero2 = double.Parse(cajaTexto.Text);
            }
            catch(Exception)
            {
                MessageBox.Show("digite un valor valido", "error");
            }
            switch (operador)
            {
                case "+":
                    resultado= suma+ numero2;
                    cajaTexto.Text = resultado.ToString();
                    suma = 0;
                    swi = true;
                    break;
                case "-":
                    if (suma != 0)
                    {
                        resultado = suma - numero2;
                        cajaTexto.Text = resultado.ToString();
                    }
                    else
                    {
                        suma = numero1 - numero2;
                        cajaTexto.Text = suma.ToString();
                    }
                    swi = true;
                    suma = 0;
                    break;
                case "*":
                    if (suma != 0)
                    {
                        resultado = suma * numero2;
                        cajaTexto.Text = resultado.ToString();
                    }
                    else
                    {
                        suma = numero1 * numero2;
                        cajaTexto.Text = suma.ToString();
                    }
                    swi = true;
                    suma = 0;
                    break;
                case "/":
                    if (suma != 0)
                    {
                        resultado = suma / numero2;
                        cajaTexto.Text = resultado.ToString();
                    }
                    else
                    {
                        suma = numero1 / numero2;
                        cajaTexto.Text = suma.ToString();
                    }
                    swi = true;
                    suma = 0;
                    break;
                case "%":
                    if (suma != 0)
                    {
                        resultado = suma %numero2;
                        cajaTexto.Text = resultado.ToString();
                    }
                    else
                    {
                        suma = numero1 % numero2;
                        cajaTexto.Text = suma.ToString();
                    }
                    swi = true;
                    suma = 0;
                    break;
                case "sen":
                    resultado =Math.Sin(numero1) ;
                    cajaTexto.Text = resultado.ToString();
                    swi = true;
                    break;
                case "cos":
                    resultado = Math.Cos(numero1);
                    cajaTexto.Text = resultado.ToString();
                    swi = true;
                    break;
                case "tan":
                    resultado = Math.Tan(numero1);
                    cajaTexto.Text = resultado.ToString();
                    swi = true;
                    break;

                case "pow":
                    if (suma != 0)
                    {
                        resultado = Math.Pow(suma, numero2);
                        cajaTexto.Text = resultado.ToString();
                    }
                    else
                    {
                        suma = Math.Pow(numero1,numero2);
                        cajaTexto.Text = suma.ToString();
                    }
                    swi = true;
                    suma = 0;
                    break;
                case "hyp":
                    if (suma != 0)
                    {
                        resultado = Math.Sqrt((Math.Pow(numero1, 2)) + Math.Pow(numero2, 2));
                        cajaTexto.Text = resultado.ToString();
                    }
                    else
                    {
                        suma = Math.Sqrt((Math.Pow(numero1, 2)) + Math.Pow(numero2, 2));
                        cajaTexto.Text = suma.ToString();
                    }
                    swi = true;
                    suma = 0;
                    break;


            }
        }

        private void button11_Click(object sender, EventArgs e)
        {
            try
            {
                operador = "%";
                numero1 = double.Parse(cajaTexto.Text);
                cajaTexto.Text = "";
            }
            catch (Exception)
            {
                MessageBox.Show("digite un valor valido", "error");
            }
        }

        private void button17_Click(object sender, EventArgs e)
        {
            try
            {
                operador = "sen";
                numero1 = double.Parse(cajaTexto.Text);
            }
            catch (Exception)
            {
                MessageBox.Show("digite un valor valido", "error");
            }
        }

        private void button20_Click(object sender, EventArgs e)
        {
            try
            {
                operador = "cos";
                numero1 = double.Parse(cajaTexto.Text);
            }
            catch (Exception)
            {
                MessageBox.Show("digite un valor valido", "error");
            }
        }

        private void button19_Click(object sender, EventArgs e)
        {
            try
            {
                operador = "tan";
                numero1 = double.Parse(cajaTexto.Text);
            }
            catch (Exception)
            {
                MessageBox.Show("digite un valor valido", "error");
            }
        }

        private void button21_Click(object sender, EventArgs e)
        {
            try
            {
                operador = "pow";
                numero1 = double.Parse(cajaTexto.Text);
                swi = true;
            }
            catch (Exception)
            {
                MessageBox.Show("digite un valor valido", "error");
            }
        }

        private void button18_Click(object sender, EventArgs e)
        {
            try
            {
                operador = "sqr";
                numero1 = double.Parse(cajaTexto.Text);
                if (suma != 0)
                {
                    suma = Math.Sqrt(suma);
                    cajaTexto.Text = suma.ToString();
                    suma = 0;
                }
                else
                {
                    suma = Math.Sqrt(numero1);
                    cajaTexto.Text = suma.ToString();
                    suma = 0;
                }
                swi = true;
            }
            catch (Exception)
            {
                MessageBox.Show("digite un valor valido", "error");
            }
        }

        private void button22_Click(object sender, EventArgs e)
        {
            if (suma != 0)
            {
                suma = Math.Pow(Math.E, suma);
                cajaTexto.Text = suma.ToString();
                suma = 0;
                swi = true;
            }
            else
            {
                numero1 = double.Parse(cajaTexto.Text);
                suma = Math.Pow(Math.E, numero1);
                cajaTexto.Text = suma.ToString();
                suma = 0;
                swi = true;
            }
        }

        private void button27_Click(object sender, EventArgs e)
        {
            double acumulador = 1;
            double contador=1;
            numero1 = double.Parse(cajaTexto.Text);
            while(contador <= numero1)
            {
                acumulador = acumulador * contador;
                contador++;

            }
            cajaTexto.Text = acumulador.ToString();
            suma = 0;
            swi = true;
        }

        private void button24_Click(object sender, EventArgs e)
        {
            try
            {
                numero1 = double.Parse(cajaTexto.Text);
                swi = true;
                operador = "hyp";
            }
            catch (Exception)
            {
                MessageBox.Show("error de operacion");
            }
        }

        private void button25_Click(object sender, EventArgs e)
        {

        }
    }
}