Lenguaje de Diseño Primer Cuatrimestre 2015 1
Programación Modular Programación Estructurada Programas fáciles de leer y modificar Técnicas de Diseños Dividir y Conquistar Estructuras de Control Algoritmos Voraces Programación Dinámica Algoritmos Exhaustivos Secuencia Condicional Iteración Dividir a un problema en subproblemas más simples Módulo Programación Modular 2
Programación Modular Enfoque de Diseño y Programación Modular Conviene Cuando una tarea específica debe ejecutarse varias veces Cuando un problema es complejo y la solución se divide o segmenta en módulos donde cada uno ejecuta una tarea específica 3
Lenguaje de Diseño: Modularización 1 2 3 t 1 - Dibujo la base. t 2 - Dibujo el poste. t 3 - Dibujo el triángulo inferior. t 4 - Dibujo el triángulo superior. 2 t 1 - Dibujo el triángulo. t 2 - Dibujo la cola. 3 t 1 - Dibujo el rectángulo. t 2 - Dibujo el triángulo. 4
Lenguaje de Diseño: Modularización 4 t 1 - Dibujo triángulo1. t 2 - Dibujo triángulo2. t 3 - Dibujo triángulo3. t 4 - Dibujo triángulo4. t 5 - Dibujo triángulo5. t 6 - Dibujo triángulo6. t 7 - Dibujo linea1. t 8 - Dibujo linea2. t 9 - Dibujo linea3. 4 5 t 1 - Dibujo rectángulo1. t 2 - Dibujo rectángulo2. t 3 - Dibujo triángulo1. t 4 - Dibujo triángulo2. t 5 - Dibujo triángulo3. t 6 - Dibujo triángulo4. 5
Lenguaje de Diseño: Modularización 1 t 1 - Dibujo la base. t 2 - Dibujo el poste. t 3 - Dibujo el triángulo inferior. t 4 - Dibujo el triángulo superior. 4 t 1 - Dibujo triángulo1. t 2 - Dibujo triángulo2. t 3 - Dibujo triángulo3. t 4 - Dibujo triángulo4. t 5 - Dibujo triángulo5. t 6 - Dibujo triángulo6. t 7 - Dibujo linea1. t 8 - Dibujo linea2. t 9 - Dibujo linea3. 2 3 5 t 1 - Dibujo el triángulo. t 2 - Dibujo la cola. t 1 - Dibujo el rectángulo. t 2 - Dibujo el triángulo. t 1 - Dibujo rectángulo1. t 2 - Dibujo rectángulo2. t 3 - Dibujo triángulo1. t 4 - Dibujo triángulo2. t 5 - Dibujo triángulo3. t 6 - Dibujo triángulo4. 6
Lenguaje de Diseño: Modularización 1 2 3 4 5 Algoritmo de dibujo del triángulo TRIAN 7
Lenguaje de Diseño: Modularización Descomposición del problema suma (unión) de pequeños problemas Se pretende: Dividirlo en pequeños problemas 4 que tengan una tarea específica. 4 sean totalmente independientes del resto. Puede suceder que dicho subproblema sea común a un conjunto de problemas de mayor envergadura. El algoritmo que lo resuelve debería ser el mismo cada vez que el subproblema esté presente en un problema. MODULARIZACIÓN DEL PROBLEMA 8
Lenguaje de Diseño: Modularización TRIAN es un algoritmo común al conjunto de problemas TRIAN es un MÓDULO 2 1 3 TRIAN 4 5 9
Lenguaje de Diseño: Modularización 3 1 t 1 - Dibujo la base. t 2 - Dibujo el poste. t 3 TRIAN t 4 - TRIAN t 1 - Dibujo el rectángulo. t 2 - TRIAN 2 t 1 TRIAN t 2 - Dibujo la cola. 4 t 1 TRIAN t 2 TRIAN t 3 TRIAN t 4 TRIAN t 5 TRIAN t 6 TRIAN t 7 - Dibujo linea1. t 8 - Dibujo linea2. t 9 - Dibujo linea3. 10
Lenguaje de Diseño: Modularización 5 t 1 - Dibujo rectángulo1. t 2 - Dibujo rectángulo2. t 3 - TRIAN t 4 - TRIAN t 5 - TRIAN t 6 - TRIAN Invocación 11
Lenguaje de Diseño: Modularización Consideraciones: - Se debe tener en cuenta el estado previo del ambiente antes de la invocación del módulo. - Se debe tener en cuenta el estado del ambiente luego de la ejecución del módulo. Ejemplo: - Se desea realizar la gráfica del farol con el uso del modulo TRIAN. - Suponga la existencia de un módulo TRIAN que grafica un triángulo equilátero. - orientación de la tortuga y recorrido que realiza para la construcción del triángulo dentro del módulo. 12
Lenguaje de Diseño: Modularización 1 Invoca a TRIAN Sale de TRIAN ERROR! Invoca a TRIAN Sale de TRIAN En Lenguaje de Diseño el concepto de Modularización se implementa con los SUBALGORITMOS 13
Ejemplo: Dado un número n entero positivo, se desea calcular e imprimir el factorial de n, n 2 y de n 3. Se debe tratar de utilizar el algoritmo para el calculo del factorial como un módulo (subalgoritmo). Nota: el algoritmo FACTORIAL permite calcular el valor factorial para un número cualquiera N ingresado por el usuario. ALGORITMO Factorial N, FACT, I: entero LEER N FACT 1 PARA I DESDE 1 HASTA N CON PASO 1 HACER PARA FACT ESCRIBIR FACT FACT * I 14
SUBALGORITMO FACTORIAL N, FACT, I: entero LEER N FACT 1 PARA I DESDE 1 HASTA N CON PASO 1 HACER PARA FACT ESCRIBIR FACT FACT * I ALGORITMO Calculo Factoriales FACTORIAL FACTORIAL FACTORIAL 15
Invocación FACTORIAL Muestra Pantalla Retorno Calculo Factoriales Tres veces se invoca el módulo FACTORIAL, quien además de calcular el factorial lo muestra por pantalla 16
Inconveniente: - se debe ingresar el número toda vez que se invoca el subalgoritmo. - alta probabilidad de cometer error en el ingreso. Se pretende: - ingresar el dato una única vez. 17
N N 2 Subalgoritmo FACTORIAL Muestra Pantalla Calculo Factoriales Algoritmo 18
ALGORITMO Calculo Factoriales N, AUX: entero LEER N AUX N FACTORIAL N AUX 2 FACTORIAL N AUX 3 FACTORIAL SUBALGORITMO Factorial FACT, I: entero FACT 1 PARA I DESDE 1 HASTA N CON PASO 1 HACER PARA FACT ESCRIBIR FACT FACT * I? 19
ALGORITMO Calculo Factoriales N, AUX: entero LEER N AUX N FACTORIAL(N) N AUX 2 FACTORIAL(N) N AUX 3 FACTORIAL(N) Es necesario poder comunicarle al subalgoritmo el valor que necesita, en este caso el valor de N SUBALGORITMO Factorial (in Nu:entero) FACT, I: entero FACT 1 PARA I DESDE 1 HASTA Nu CON PASO 1 HACER PARA FACT ESCRIBIR FACT FACT * I 20
Supongamos que se desea sacar del módulo FACTORIAL la tarea de mostrar por pantalla Invocación Retorno Muestra FACTORIAL Es necesario que el módulo devuelva el resultado para que, desde el algoritmo se muestre por pantalla Calculo Factoriales Pantalla 21
ALGORITMO Calculo Factoriales N, AUX, FACT: entero LEER N AUX N FACTORIAL(N, FACT) ESCRIBIR FACT N AUX 2 FACTORIAL(N, FACT) ESCRIBIR FACT N AUX 3 FACTORIAL(N, FACT) ESCRIBIR FACT Calculo Factoriales Invocación Retorno Muestra FACTORIAL Pantalla 22
ALGORITMO Calculo Factoriales N, AUX, FACT: entero LEER N AUX N FACTORIAL(N, FACT) ESCRIBIR FACT N AUX 2 FACTORIAL(N, FACT) ESCRIBIR FACT N AUX 3 FACTORIAL(N, FACT) ESCRIBIR FACT SUBALGORITMO Factorial (in NU:entero, out FA:entero) I: entero FA 1 PARA I DESDE 1 HASTA NU CON PASO 1 HACER FA PARA Qué función cumple NU y FA? FA * I 23
ALGORITMO Calculo Factoriales Parámetros Actuales N, AUX, FACT: entero LEER N AUX N FACTORIAL(N, FACT) ESCRIBIR FACT N AUX 2 FACTORIAL(N, FACT) ESCRIBIR FACT N AUX 3 FACTORIAL(N, FACT) ESCRIBIR FACT 24
SUBALGORITMO Factorial (in NU:entero, out FA:entero) I: entero FA 1 PARA I DESDE 1 HASTA NU CON PASO 1 HACER FA PARA FA * I Parámetros Formales 25
FACTORIAL( N, FACT ) Invocación SUBALGORITMO Factorial (in NU:entero, out FA:entero) Definición Los parámetros Formales se definen: 4 in, son sólo parámetros de ingreso de datos. 4 out, solo parámetros de salida de datos. 4 in out, a través de ellos se ingresan los datos al subalgoritmo y el subalgoritmo devuelve información. 26
Restricciones: Si el parámetro formal fue definido 4 in, los parámetros actuales solo pueden ser constantes, variables, expresiones o valores de funciones. 4 out o in out, los parámetros actuales deben estar definidos en el ámbito del algoritmo invocante pues es allí donde se debe retornar los resultados. 27
- Ámbito ALGORITMO Calculo Factoriales Ambito para N, AUX, FACT N, AUX, FACT: entero LEER N AUX N FACTORIAL(N, FACT) ESCRIBIR FACT N AUX 2 FACTORIAL(N, FACT) ESCRIBIR FACT N AUX 3 FACTORIAL(N, FACT) ESCRIBIR FACT Ámbito de una variable (en inglés scope: alcance) es el contexto o zona del programa en que la misma está definida y por lo tanto puede ser accedida y utilizada. 28
SUBALGORITMO Factorial (in NU:entero, out FA:entero) Ámbito sólo para NU, FA, I I: entero FA 1 PARA I DESDE 1 HASTA NU CON PASO 1 HACER FA PARA FA * I 29
Formalmente: SUBALGORITMO <Nombre_subalgoritmo> (<lista de parámetros>) <cuerpo del subalgoritmo> Donde la declaración de cada parámetro debe tener los siguiente datos: < clase de parámetro > < nbre_par > : <tipo_de_dato_vble> in out in out Entero Real Carácter Lógico Arreglo de.. 30
Ejemplos: Invocación? SUBALGORITMO Factorial (in N:entero, out FACT:entero) SUBALGORITMO Ordeno (inout V: arreglo de entero, in M, N: entero) SUBALGORITMO Mult (in A: real, inout B: entero, out N: real) 31
Ejemplo 2: ALGORITMO GASTOS li, ls, c: entero limite: entero suma: real ImpuestosB: arreglo [1..24] de real Cadena: arreglo [1.. 25] de caracter li 1 ls 15 suma 0,0 ESCRIBIR Ingrese codigo del impuesto (1-Gas, 2-Patente): LEER c BUSCA (2, ImpuestosB, ls, suma) BUSCA (c, ImpuestosB, li, ls, suma + 2) BUSCA (c, ls, ImpuestosB, li, suma) BUSCA (suma, ImpuestosB, ls, x) SUBALGORITMO BUSCA (in cod: entero, in A: arreglo de real, in x: entero, j: entero. in y: entero, inout z: entero) 32
Ejemplo3: ALGORITMO GASTOS li, ls, c: entero limite: entero suma: real ImpuestosB: arreglo [1..24] de real Cadena: arreglo [1.. 25] de caracter li 1 ls 15 suma 0,0 SUBALGORITMO INGRESO (< Parámetros? >). ESCRIBIR Cuantos caracteres ingresara? LEER y PARA j DESDE x HASTA y CON PASO 1 HACER LEER A[j] PARA ESCRIBIR Ingrese codigo del impuesto (1-Gas, 2-Patente): LEER c ESCRIBIR El total pagado del impuesto INGRESO (< Parámetros actuales? >) ESCRIBIR Ingreso:, limite, caracteres 33
Ejemplo 4: Que hace esta parte del siguiente algoritmo? ALGORITMO EJEMPLO 2 Cur_A: arreglo [1..30] de entero I, Valor: entero PARA I DESDE 1 HASTA 30 CON PASO 1 HACER ESCRIBIR Ingrese Nota LEER Cur_A [I] MIENTRAS (Cur_A[I] < 1 v Cur_A [I] > 10) HACER ESCRIBIR Ingrese Nota LEER Cur_A [I] MIENTRAS PARA... Lenguaje de Diseño: Subalgoritmos Se ingresan 30 valores enteros en un arreglo llamado Cur_A (supongamos un Curso A). Como se debería modificar este algoritmo si además se desea cargar las notas del Curso B que tiene 45 alumnos? 34
ALGORITMO EJEMPLO 2 Cur_A: arreglo [1..30] de entero Cur_B: arreglo [1..45] de entero I, Valor: entero PARA I DESDE 1 HASTA 30 CON PASO 1 HACER ESCRIBIR Ingrese Nota LEER Cur_A [I] MIENTRAS (Cur_A[I] < 1 v Cur_A [I] > 10) HACER ESCRIBIR Ingrese Nota LEER Cur_A [I] MIENTRAS PARA Como modificamos este algoritmo si además tenemos que cargar las notas del Curso C, D, etc? PARA I DESDE 1 HASTA 45 CON PASO 1 HACER ESCRIBIR Ingrese Nota LEER Cur_B [I] MIENTRAS (Cur_B[I] < 1 v Cur_B [I] > 10) HACER ESCRIBIR Ingrese Nota LEER Cur_B[I] MIENTRAS PARA. Lenguaje de Diseño: Subalgoritmos 35
ALGORITMO EJEMPLO 2 Cur_A: arreglo [1..30] de entero Cur_B: arreglo [1..45] de entero I, Valor: entero PARA I DESDE 1 HASTA 30 CON PASO 1 HACER ESCRIBIR Ingrese Nota LEER Cur_A [I] MIENTRAS (Cur_A[I] < 1 v Cur_A [I] > 10) HACER Qué tienen en común estas dos porciones de código? ESCRIBIR Ingrese Nota LEER Cur_A [I] PARA I DESDE 1 HASTA 45 CON PASO 1 HACER MIENTRAS ESCRIBIR Ingrese Nota PARA LEER Cur_B [I] MIENTRAS (Cur_B[I] < 1 v Cur_B [I] > 10) HACER ESCRIBIR Ingrese Nota LEER Cur_B[I] MIENTRAS PARA.. 36
ALGORITMO EJEMPLO 2 Cur_A: arreglo [1..30] de entero Cur_B: arreglo [1..45] de entero I, Valor: entero PARA I DESDE 1 HASTA 30 CON PASO 1 HACER ESCRIBIR Ingrese Nota LEER Cur_A [I] MIENTRAS (Cur_A[I] < 1 v Cur_A [I] > 10) HACER Qué tienen diferente estas dos porciones de código? ESCRIBIR Ingrese Nota LEER Cur_A [I] PARA I DESDE 1 HASTA 45 CON PASO 1 HACER MIENTRAS ESCRIBIR Ingrese Nota PARA LEER Cur_B [I] MIENTRAS (Cur_B[I] < 1 v Cur_B [I] > 10) HACER ESCRIBIR Ingrese Nota LEER Cur_B[I] MIENTRAS PARA.. Solución: definimos un subalgoritmo con la tarea que se repite y los datos que cambian lo comunicamos como parámetro 37
Definimos un Subalgoritmo que va a realizar el Llenado del Arreglo ALGORITMO EJEMPLO 2 Cur_A: arreglo [1..30] de entero Cur_B: arreglo [1..45] de entero I, Valor: entero Llenado (Cur_A, 1, 30 ) Llenado (Cur_B, 1, 45)... Invocación 38
SUBALGORITMO Llenado (inout C: arreglo de entero, in M, N: entero) I: entero PARA I DESDE M HASTA N CON PASO 1 HACER PARA ESCRIBIR Ingrese Nota LEER C[I] MIENTRAS (C[I] < 1 v C[I] > 10) HACER ESCRIBIR Ingrese Nota LEER C[I] MIENTRAS 39
Como modificamos este algoritmo si la cantidad de alumnos del Curso C varia ( nunca supera los 30 )? ALGORITMO EJEMPLO 2 Cur_A: arreglo [1..30] de entero Cur_B: arreglo [1..45] de entero Cur_C: arreglo [1..30] de entero Cur_D: arreglo [1..30] de entero I, Valor: entero Llenado (Cur_A, 1, 30 ) Llenado (Cur_B, 1, 45 ) ESCRIBIR Cuantos Alumnos tiene el Curso C LEER Valor Llenado (Cur_C, 1, Valor ) Llenado (Cur_D, 1, 30 )... Faltan controles!!! 40
SUBALGORITMO Llenado (in out C: arreglo de entero, in M, N: entero) I: entero PARA I DESDE M HASTA N CON PASO 1 HACER PARA ESCRIBIR Ingrese Nota LEER C[I] MIENTRAS (C[I] < 1 v C[I] > 10) HACER ESCRIBIR Ingrese Nota LEER C[I] MIENTRAS 41
Como modificamos este algoritmo si vamos a cargar las notas a partir del alumno 10 hasta el 20 en el Curso D? SUBALGORITMO Llenado (in out C: arreglo de entero, in M, N: entero) I: entero PARA I DESDE M HASTA N CON PASO 1 HACER ESCRIBIR Ingrese Nota LEER C[I] PARA MIENTRAS (C[I] < 1 v C[I] > 10) HACER ESCRIBIR Ingrese Nota LEER C[I] MIENTRAS ALGORITMO EJEMPLO 2 Cur_A: arreglo [1..30] de entero Cur_B: arreglo [1..45] de entero Cur_C: arreglo [1..30] de entero Cur_D: arreglo [1..30] de entero I, Valor: entero Llenado (Cur_A, 1, 30 ) Llenado (Cur_B, 1, 45 ) ESCRIBIR Cuantos Alumnos tiene el Curso C LEER Valor Llenado Llenado (Cur_C, 1, Valor ) (Cur_D, 10, 20 ) 42
Ejemplo: Intercambiar el contenido de dos variables enteras. El algoritmo deberá ser diseñado como subalgoritmo denominado Intercambio. Solución: - Intercambiar los contenidos mediante la ayuda de una variable auxiliar que almacene temporariamente el contenido de una de ellas. Ejemplo: estado inicial: 21 35? A B Aux 1º acción: 21 35 21 A B Aux 2º acción: 35 35 21 A B Aux 3º acción: 35 21 21 A B Aux 43
Objetos: Variables? Parámetros? A - variable entera con el primer dato. B - variable entera con el segundo dato. AUX - variable auxiliar. SUBALGORITMO Intercambio ( ) 44
Algoritmo Depurado: SUBALGORITMO Intercambio ( inout A,B:entero ) AUX: entero AUX A A B B AUX Clase de Parámetros? in out in out 45
Lenguaje d Ejercicio: Analice el siguiente algoritmo. Se pide que defina (en forma completa) los parámetros formales, parámetros actuales y las definiciones de variables correspondientes para un buen funcionamiento del mismo SUBALGORITMO Ingreso ( ) ESCRIBIR INGRESE LA CANTIDAD DE CARACTERES LEER LS MIENTRAS LS <=0 v LS > 100 HACER ESCRIBIR INGRESE CANTIDAD LEER LS VECES VECES + 1 MIENTRAS I LI MIENTRAS I <= LS HACER ESCRIBIR INGRESE CARACTER LEER ARR[I] I I + 1 MIENTRAS ALGORITMO AL Acar: arreglo [1..100] de caracter LI, LS, ERROR: entero LI 1 Ingreso ( ) ESCRIBIR Ingreso, ERROR, veces un valor incorrecto 46
47