Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Contenido
CAPITULO 3 PROCEDIMIENTOS Y FUNCIONES .................................................... 173
PROCEDIMIENTO ......................................................................................... 173
1.4.1 Procedimientos sub ................................................................................. 173
1.4.2 Procedimientos function ........................................................................... 173
1.4.3 Sintaxis de la declaración ........................................................................ 173
1.4.4 La instrucción return ................................................................................ 174
LLAMADA A UNA FUNCION O PROCEDIMIENTO....................................... 174
1.2 1 Ejemplo1. Calcular el área de un circulo usando funciones. .................... 175
AGREGAR UN MODULO PARA ALMACENAR PROCEDIMIENTOS ........... 175
PASE DE PARAMETROS POR VALOR Y POR REFERENCIA ................... 175
1.4.1 Pase de parámetros por valor. ................................................................. 176
1.4.2 Pase de parametros por referencia- Ej. intercambiar dos valores. ........ 176
EJEMPLO DE FUNCIONES .......................................................................... 177
1.5.1 Funciones que devuelven numeros enteros ............................................ 177
1.5.2 Funciones de devuelven un tipo de tipo single ....................................... 179
EJEMPLO DE PROCEDIMIENTOS SUB ....................................................... 179
1. Dibujar un cuadro, dado la localización x1,y1 y el tamaño que es ancho y alto (
el color se maneja de afuera ................................................................................. 180
.6.1- El siguiente programa dibuja una torre de 5 escalones ................................ 182
1.6.2 Tarea 4. Usando la función cuadro Dibuje un tablero de ajedrez ,Modifique
el programa principal para que dibuje varios tableros de ajedrez de diferentes
colores y tamaños ................................................................................................. 183
1.4.5 ajedrez(cx,cy,ancho,alto,color1,color2), ................................................... 184
1.6.3 Tarea 5. Usando la función cuadro y marco dibuje un enladrillado .......... 186
1.6.4 Tarea. Graficar 16 cuadritos de colores como se muestra en la figura .... 187
1.6.5 Tarea: Grafique un cuadro en el interior de otro como se muestra ......... 188
1.6.6 Ejercicios de procedimientos sub dibujar un modelo y repetirlo ............. 189
1.6.7 Procedimientos sub ................................................................................. 191
1.4.6 Usando la función dibuje triángulos como la mostrada ............................ 193
Funciones que devuelven cadenas ............................................................... 194
d) Funciones de tipo boolean .- Encontrar los primeros n números primos.. 194
Funciones que devuelven valores enteros.- Ver el problema de factorial ...... 195
Funciones de tipo real . ............................................................................... 196
1.6.8 14 resolver una función de la forma f(x) == x * x + y * y........................... 197
e) Funciones de tipo double.- ...................................................................... 199
Ejemplos de tipos de parámetros ................................................................ 199
1.6.9 Procedimientos sin parámetros ............................................................... 200
1.6.10 Ejemplo 1. Menú de las 4 operaciones .................................................. 200
1.6.11 Ejemplo 2 Parametros de tipo string.- Pasar un carácter y imprimir 10
veces 200
FUNCIONES CON EL MISMO NOMBRE (Sobrecarga de funciones) ....... 202
ACCESIBILIDAD DE LAS VARIABLES. AMBITO ...................................... 203
1.6.12 Variable global.- existe y tiene valor desde el principio hasta el final de la
ejecución del programa. ...................................................................................... 203
1.6.13 Variable local.- ........................................................................................ 203
1.6.14 Ejemplo 2 Ámbito con funciones ............................................................. 203
FUNCIONES CON ARGUMENTOS POR DEFECTO ................................ 203
1.6.15 Variables locales estáticas.- Conservan su valor cuando salen de la
función 204
- RECURSIVIDAD ..................................................................................... 204
1.6.16 3.9.1 Recursividad directa.-..................................................................... 204
1.6.17 Ejemplo 2: función recursiva de tipo void ................................................ 205
1.6.18 3 Recursividad indirecta .......................................................................... 206
PROBLEMAS RESUELTOS ...................................................................... 207
1.6.19 Problema C301.- Calcular el Área de un rectángulo usando funciones. . 207
1.6.20 Problema C302.- Encontrar el cubo de un número encontrando primero el
área: 207
1.6.21 Problema C303. Encontrar la combinatoria nCr = n!/(r!*(n-r)! ................. 208
1.6.22 Problema C304.- Funciones que devuelven varios valores .................... 208
1.6.23 Problema C305.- Usando funciones elabore un menú de las 4 operaciones
aritméticas básicas ............................................................................................... 209
1.6.24 Problema C306.- Elaborar tablas de Interés para calcular el valor futuro
que se obtiene por la fórmula F= (1+i)n donde n = número de periodos i= tasa de
interés el programa debe leer la tasa de interés inicial, tasa de interés final, la
variación de la tasa y el número de periodos ...................................................... 210
1.6.25 Problema C307.- Usando funciones dibujar cuadros de colores que
aparecen en la pantalla en forma aleatoria. ......................................................... 211
1.6.26 Problema C308- Recursividad indirecta .................................................. 212
1.6.27 Problema C309..- Torres de Hanoi ......................................................... 212
1.6.28 Problema C310.-Números de Fibonacci con recursividad ...................... 213
1.6.29 Problema C311 Usando funciones calcular la suma de n términos de la
serie .Se debe ingresar x y n. ............................................................................... 214
1.6.30 Problema C312 Dibujar un cuadro usando solo recursividad.................. 215
1.6.31 Problema C313 Calcule los valores de una funcion f(x) usando solo
recursividad .......................................................................................................... 215
Programacion y métodos numéricos 2019 A\ Funciones / Ismael Véliz Vilca - 171 -
1.6.32 Problema C314 Calcule los valores de una función f(x,y) usando solo
recursividad ........................................................................................................... 216
1.6.33 ProblemaC315. Invertir un número usando recursividad ......................... 217
1.6.34 Problema C316. Escriba una función para encontrar el máximo divisor de
2 números ............................................................................................................. 217
1.6.35 El problema de mcd se puede resolver también usando recursividad ..... 218
1.6.36 Problema C318 . modifique el programa línea para dibujar cubos rellenos
de colores Tarea dibujo cubos en modelo de alambre como la mostrada ............ 218
1.6.37 Problema C319 Usando la función linea del programa anterior dibuje un
espiral creciente y en movimiento ......................................................................... 219
1.6.38 Problema C320 . usando la funcion linea dibuje un diseño como la
mostrada ............................................................................................................... 220
.-PROBLEMAS PROPUESTOS .................................................................. 221
EXAMENES RESUELTOS.......................................................................... 222
1.6.39 Problema 1 . Dibujar cuatro casitas de menor a mayor tamaño y diferentes
colores de diferentes bordes y rellenos como se muestra en la figura (sugerencia
use la función línea hecho en clase) ..................................................................... 222
1.6.40 Problema 3 : Usando recursividad calcule la sumatoria de a hasta b ...... 225
1.6.41 Dibuje un arbol usando funciones ............................................................ 225
1.6.42 Usando la funcion arbol dibuje arboles en diferente localizacion y de
diferentes alturas y anchos y de diferentes colores .............................................. 226
1.6.43 3 Dibujar una cancha de tenis con funciones .......................................... 227
1.6.44 4 Reconocer animal ................................................................................. 228
1.6.45 5. Diagnosticar falla ................................................................................. 229
1.6.46 DIBUJAR UN VELERO Y QUE SE MUEVA ( EL Barco pasa por delante a
otro barco, el barco pása por detrás de otro barco ............................................. 229
1.6.47 Ejercicios de recursividad ....................................................................... 231
1.6.48 Programar un algoritmo recursivo que permita hacer la división por restas
sucesivas. ............................................................................................................. 231
1.6.49 Ejercicio 5. Programar un algoritmo recursivo que permita sumar los dígitos
de un número. Ejemplo: Entrada: 123 Resultado:6 .............................................. 232
1.6.50 Ejercicio 6 tabla de multiplicar con recursividad ...................................... 232
1.6.51 7. Dibuje un cubo usando la funcion linea ............................................... 233
1.6.52 8 dibujar el cubo rellenado ....................................................................... 234
1.6.53 9 Dibujar un poligono regular ................................................................... 236
1.6.54 10 Diseñe un figura de su creación y haga mover la figura ..................... 236
1.6.55 11. Modificar el programa para imprimir varios carritos de colores .......... 238
1.6.56 12 Coordenadas polares polígono que se mueve.................................. 238
1.6.57 Se tiene una mesa de billar se ingresa el punto inicial (x1,y1) de la bola y
la pendiente , elaborar un programa que dibuje la trayectoria de la bola ( después
de un cierto tiempo se estabiliza) ........................................................................ 240
1.6.58 14 Dibujar un Robot ................................................................................ 241
1.6.59 15 Dibujar un circulo ............................................................................... 242
1.6.60 Ejercicio 10. Programar un algoritmo recursivo que determine si un número
es positivo. ........................................................................................................... 243
1.6.61 Ejercicio 11. Programar un algoritmo recursivo que determine si un número
es impar utilizando recursividad cruzada. ............................................................ 244
1.6.62 12. RECURSIVIDAD elabore el siguiente cuadro con recursividad ........ 244
1.6.63 13. elabore la siguiente aplicación usando recursividad ......................... 246
1.6.64 14. Usando recursividad construya la siguiente figura ............................ 246
1.6.65 8 Dibujar una línea con recursividad ....................................................... 248
1.6.66 Sumar con cadenas ................................................................................ 249
1.6.67 Funciones de suma ................................................................................. 249
1.6.68 Integral recursive ..................................................................................... 250
1.6.69 ANGULO DE GIRO. ................................................................................ 252
1.6.70 Genrar 3 numeros en foma en forma aleatoria y de acuerdo a ella llamar a
3 funciones ........................................................................................................... 253
Programacion y métodos numéricos 2019 A\ Funciones / Ismael Véliz Vilca - 173 -
PROCEDIMIENTO
Un procedimiento Sub es una serie de instrucciones de Visual Basic delimitadas por las
instrucciones Sub y End Sub.
Sintaxis de la declaración
Las funciones dividen tareas grandes de computación en varias más pequeñas permite
la posibilidad de construir sobre lo que otros ya han hecho en comenzar en lugar de
comenzar desde cero. Las funciones apropiadas ocultan los detalles de operación de
las partes del programa que no necesitan saber acerca de ellos, así que dan claridad
a la totalidad y facilitan la penosa tarea de hacer cambios.
[ variable=] expresión([parametros-actuales]);
expresión.- Especifica una dirección que referencia a una función. Esto significa que
una función puede ser llamada a través de un puntero a una función. La expresión es
el nombre de la función.
parámetros actuales.- Son una lista de expresiones separadas por comas. Los
valores resultantes son pasados a la función y asignados a sus correspondientes
Programacion y métodos numéricos 2019 A\ Funciones / Ismael Véliz Vilca - 175 -
Module Module1
Function Area(ByVal rad As Single) As Single
Dim super As Single
super = CSng(Math.PI * rad * rad)
Return super
End Function
Sub Main()
Dim radio, superficie As Single
Console.Write("Ingrese radio ")
radio = CSng(Console.ReadLine())
superficie = Area(radio)
Console.WriteLine("Radio {0} superficie {1}", radio, superficie)
Console.ReadLine()
End Sub
End Module
Module Module1
Function fact(ByVal N As Integer) As Integer
Dim f = 1, i As Integer
For i = 1 To N
f=f*i
Next
Return f
End Function
Sub Main()
Dim n As Integer
Console.Write("Ingrese un numero ")
n = CInt(Console.ReadLine())
Console.WriteLine("El factorial de {0} es {1} ", n, fact(n))
Console.ReadLine()
End Sub
End Module
- Los datos que se pasa a la función son copias de los datos reales. En el ejemplo del
área del circulo se tiene que el parámetro es rad:val
El parámetro es byval
Ejemplo
Module Module1
Sub cambiar(ByVal a As Single, ByVal b As Single)
Dim temp As Single
temp = a
a=b
b = temp
End Sub
Sub main()
Dim x As Single = 10, y As Single = 50
Console.WriteLine("pase de parametros por valor antes x= {0} y ={1} ", x, y)
cambiar(x, y)
Console.WriteLine("Despues x= {0} y ={1} ", x, y)
Console.ReadLine()
End Sub
End Module
Module Module1
Console.ReadLine()
End Sub
End Module
EJEMPLO DE FUNCIONES
parámetros
valor que
devuelve integer single char string boolean
Integer
single
Char
string
boolean
Module Module1
Function sumar(ByVal n As Integer) As Integer
Dim i As Integer = 1, s As Integer = 0
For i = 1 To n
s=s+i
Next
Return s
End Function
Sub main()
Dim n As Integer
Console.Write("ingrese n ")
n = CInt(Console.ReadLine())
Console.WriteLine("la suma de 1 hasta {0} es {1} ", n, sumar(n))
Console.ReadLine()
End Sub
End Module
Module Module1
Function aleatorioentre(ByVal a As Integer, ByVal b As Integer) As Integer
Return CInt(a + (Rnd() * Math.Abs(b - a)))
End Function
Sub main()
Dim li As Integer = -10, ls As Integer = 20, n As Integer = 15, i As Integer
Randomize()
For i = 1 To n
Console.Write("{0} ", aleatorioentre(li, ls))
Next
Console.ReadLine()
End Sub
End Module
Module Module1
Function promedio2altasnotas(ByVal a As Integer, ByVal b As Integer, ByVal c As
Integer) As Single
Dim menor As Single = a, promedio As Single
If (b < menor) Then menor = b
If (c < menor) Then menor = c
promedio = (a + b + c - menor) / 2
Return promedio
End Function
Sub main()
Dim n1 As Integer, n2 As Integer, n3 As Integer
Console.WriteLine("ingrese 3 notas enteras")
n1 = CInt(Console.ReadLine())
n2 = CInt(Console.ReadLine())
n3 = CInt(Console.ReadLine())
Console.WriteLine("el promedio de las dos altas notas es {0}",
promedio2altasnotas(n1, n2, n3))
Console.ReadLine()
End Sub
End Module
Module Module1
Function suma(ByVal x As Single, ByVal y As Single) As Single
Return x + y
End Function
Sub main()
Dim a As Single, b As Single, r As Single
Console.WriteLine("Ingrese dos numeros ")
a = CSng(Console.ReadLine())
b = CSng(Console.ReadLine())
r = suma(a, b)
Console.WriteLine("la suma es es {0} ", r)
Console.ReadLine()
End Sub
End Module
Tarea encuentre la combinatoria nCr usando la función factorial
Module Module1
Sub cuadro(ByVal cx As Integer, ByVal cy As Integer, ByVal ancho As Integer, ByVal
alto As Integer)
Dim fila As Integer, col As Integer
For fila = 0 To alto - 1
For col = 0 To ancho - 1
Console.SetCursorPosition(cx + col, cy + fila)
Console.WriteLine("*")
Next
Next
End Sub
Sub main()
Dim x1 As Integer ' columna inicial del cuadro
Dim y1 As Integer ' fila inicial del cuadro
Dim ancho As Integer ' ancho del caudro
Dim alto As Integer ' alto del cuadro
x1 = 10 : y1 = 2 : ancho = 20 : alto = 10
cuadro(x1, y1, ancho, alto)
'dibujamos otros cuadro pero en otralocalizacion y otro tamaño
Console.ForegroundColor = ConsoleColor.Red ' puede se 12
Console.BackgroundColor = ConsoleColor.Green ' puede se 10
Console.ReadLine()
Programacion y métodos numéricos 2019 A\ Funciones / Ismael Véliz Vilca - 181 -
End Sub
End Module
2. DIBUJE un marco con las mismas caracteristicas del cuadro anterior
Module Module1
Sub marco(ByVal cx As Integer, ByVal cy As Integer, ByVal ancho As Integer, ByVal
alto As Integer)
Dim fila, col As Integer
For col = 0 To ancho - 1
Console.SetCursorPosition(cx + col, cy)
Console.WriteLine("*")
Console.SetCursorPosition(cx + col, cy + alto)
Console.WriteLine("*")
Next
For fila = 0 To alto
Console.SetCursorPosition(cx, cy + fila)
Console.WriteLine("*")
Console.SetCursorPosition(cx + ancho, cy + fila)
Console.WriteLine("*")
Next fila
End Sub
Sub main()
Dim x1 As Integer ' columna inicial del cuadro
Dim y1 As Integer ' fila inicial del cuadro
Dim ancho As Integer ' ancho del caudro
Dim alto As Integer ' alto del cuadro
x1 = 10 : y1 = 2 : ancho = 20 : alto = 10
marco(x1, y1, ancho, alto)
'dibujamos otros cuadro pero en otralocalizacion y otro tamaño
Console.ForegroundColor = ConsoleColor.Red ' puede se 12
Console.BackgroundColor = ConsoleColor.Green ' puede se 10
Console.ReadLine()
End Sub
End Module
Module Module1
Sub cuadro(ByVal cx As Integer, ByVal cy As Integer, ByVal ancho As Integer, ByVal
alto As Integer)
Dim fila As Integer, col As Integer
For fila = 0 To alto - 1
For col = 0 To ancho - 1
Console.SetCursorPosition(cx + col, cy + fila)
Console.WriteLine("*")
Next
Next
End Sub
Sub main()
Console.BackgroundColor = CType(9, ConsoleColor)
Console.ForegroundColor = CType(9, ConsoleColor)
cuadro(35, 1, 10, 4)
Console.BackgroundColor = CType(10, ConsoleColor)
Console.ForegroundColor = CType(10, ConsoleColor)
cuadro(30, 5, 20, 4)
Console.BackgroundColor = CType(11, ConsoleColor)
Console.ForegroundColor = CType(11, ConsoleColor)
cuadro(25, 9, 30, 4)
Console.BackgroundColor = CType(12, ConsoleColor)
Programacion y métodos numéricos 2019 A\ Funciones / Ismael Véliz Vilca - 183 -
Sub main()
Dim cx As Integer = 40, cy As Integer = 1, alto As Integer = 2, ancho As Integer =
3, i As Integer
For i = 1 To 12
Console.BackgroundColor = 16 - i
Console.ForegroundColor = 16 - i
cuadro(cx - ancho * i, cy + alto * i - alto, i * ancho * 2, alto)
Next
Console.ReadLine()
End Sub
Sub main()
Dim fila As Integer, col As Integer
Dim cx As Integer = 1, cy As Integer = 1
Dim ancho As Integer = 8, alto As Integer = 3
Dim color As Integer
For fila = 1 To 8
For col = 1 To 8
If (fila + col) Mod 2 = 0 Then
color = 12
Else
color = 9
End If
Console.BackgroundColor = CType(color, ConsoleColor)
Console.ForegroundColor = CType(color, ConsoleColor)
cuadro(cx + col * ancho, cy + fila * alto - alto, ancho, alto)
Next
Next
Console.ReadLine()
End Sub
End Module
1.4.5 ajedrez(cx,cy,ancho,alto,color1,color2),
Programacion y métodos numéricos 2019 A\ Funciones / Ismael Véliz Vilca - 185 -
Module Module1
Sub cuadro(ByVal cx As Integer, ByVal cy As Integer, ByVal ancho As Integer, ByVal
alto As Integer)
Dim fila As Integer, col As Integer
For fila = 0 To alto - 1
For col = 0 To ancho - 1
Console.SetCursorPosition(cx + col, cy + fila)
Console.WriteLine("*")
Next
Next
End Sub
Sub ajedrez(ByVal cx As Integer, ByVal cy As Integer, ByVal ancho As Integer, _
ByVal alto As Integer, ByVal c1 As Integer, ByVal c2 As Integer)
Dim fila As Integer, col As Integer, color As Integer
For fila = 1 To 8
For col = 1 To 8
If (fila + col) Mod 2 = 0 Then
color = c1
Else : color = c2
End If
Console.BackgroundColor = CType(color, ConsoleColor)
Console.ForegroundColor = CType(color, ConsoleColor)
cuadro(cx + col * ancho, cy + fila * alto, ancho, alto)
Next
Next
End Sub
Sub main()
While (True)
ajedrez(1, 1, 3, 2, 9, 12)
ajedrez(30, 1, 3, 2, 10, 14)
ajedrez(60, 1, 1, 1, 11, 13)
System.Threading.Thread.Sleep(50)
ajedrez(1, 1, 3, 2, 12, 9)
ajedrez(30, 1, 3, 2, 9, 12)
ajedrez(60, 1, 1, 1, 13, 11)
End While
End Sub
End Module
Tarea.- Modificar el programa principal para mover el tablero
Sub main()
Dim i As Integer
For i = 1 To 50
ajedrez(i, 1, 3, 2, 9, 12)
System.Threading.Thread.Sleep(50)
ajedrez(i, 1, 3, 2, 0, 0)
Next
Console.ReadLine()
End Sub
Module Module1
Sub marco(ByVal cx As Integer, ByVal cy As Integer, ByVal ancho As Integer, ByVal
alto As Integer)
Dim fila, col As Integer
For col = 0 To ancho - 1
Console.SetCursorPosition(cx + col, cy)
Console.WriteLine("*", 219)
Console.SetCursorPosition(cx + col, cy + alto)
Console.WriteLine("*", 219)
Next
For fila = 0 To alto
Console.SetCursorPosition(cx, cy + fila)
Console.WriteLine("*")
Console.SetCursorPosition(cx + ancho, cy + fila)
Console.WriteLine("*")
Next fila
End Sub
Next
End Sub
Sub main()
Dim nf As Integer = 5, nc As Integer = 8, ancho As Integer = 8
Dim alto As Integer = 4, Cx As Integer = 1, Cy As Integer = 1, x1 As Integer
Dim fila, col As Integer
For fila = 1 To nf
For col = 1 To nc
If (fila Mod 2 = 0) Then
x1 = Cx
Else : x1 = CInt(Cx + ancho / 2)
End If
Console.BackgroundColor = CType(12, ConsoleColor)
Console.ForegroundColor = CType(12, ConsoleColor)
cuadro(x1 + col * ancho, Cy + fila * alto, ancho, alto)
Console.ForegroundColor = CType(14, ConsoleColor)
Console.BackgroundColor = CType(14, ConsoleColor)
marco(x1 + col * ancho, Cy + fila * alto, ancho, alto)
Next
Next
Console.ReadLine()
End Sub
End Module
1.6.4 Tarea. Graficar 16 cuadritos de colores como se muestra en la figura
Sub main()
Dim fila, col As Integer, cont As Integer = 0, ancho As Integer = 8, alto As Integer = 4
Dim cx As Integer = 1, cy As Integer = 1
For fila = 1 To 4
For col = 1 To 4
Console.BackgroundColor = CType(cont, ConsoleColor)
Console.ForegroundColor = CType(cont, ConsoleColor)
cuadro(cx + col * ancho, cy + fila * alto, ancho, alto)
cont += 1
Next
Next
Console.ReadLine()
End Sub
Module Module1
Sub cuadro(ByVal cx As Integer, ByVal cy As Integer, ByVal ancho As Integer, ByVal
alto As Integer)
Dim fila, col As Integer
For fila = 0 To alto - 1
For col = 0 To ancho - 1
Console.SetCursorPosition(cx + col, cy + fila)
Console.WriteLine("*")
Next
Next
End Sub
Sub main()
Dim i As Integer, n As Integer = 12
Dim cont As Integer = 15, ancho As Integer = 40, alto As Integer = 24, cx As
Integer = 40, cy As Integer = 1
While (True)
For i = 1 To n
If (cont > 0) Then
cont -= 1
Else
cont = 15
End If
Console.BackgroundColor = CType(cont, ConsoleColor)
Console.ForegroundColor = CType(cont, ConsoleColor)
cuadro(cx - (ancho - i), cy + i, ancho - i * 2, alto - i * 2)
Programacion y métodos numéricos 2019 A\ Funciones / Ismael Véliz Vilca - 189 -
System.Threading.Thread.Sleep(100)
Next
Console.ReadLine()
End While
Console.ReadLine()
End Sub
End Module
Module Module1
Sub objeto(ByVal cx As Integer, ByVal cy As Integer, ByVal ancho As Integer, ByVal
alto As Integer, _
ByVal tipo As Integer, ByVal color As Integer)
Dim col As Integer, fila As Integer, pasox As Integer = 1, pasoy As Integer = 1
Console.BackgroundColor = CType(color, ConsoleColor)
Console.ForegroundColor = CType(color, ConsoleColor)
Select Case tipo
Case 1 : pasox = 1
pasoy = 1
Case 2 : pasox = -1
pasoy = 1
Case 3 : pasox = 1
pasoy = -1
Case 4 : pasox = -1
pasoy = -1
End Select
For fila = 0 To alto
For col = ancho - fila To 0 Step -1
Console.SetCursorPosition(cx + col * pasox, cy + fila * pasoy)
Console.WriteLine("*", 219)
Next
Next
End Sub
Sub modelo(ByVal cx As Integer, ByVal cy As Integer, ByVal ancho As Integer, ByVal
alto As Integer)
objeto(cx, cy, ancho, alto, 1, 10)
objeto(cx, cy, ancho, alto, 2, 13)
objeto(cx, cy, ancho, alto, 3, 14)
objeto(cx, cy, ancho, alto, 4, 15)
objeto(cx + ancho, cy - alto, ancho, alto, 2, 1)
objeto(cx + ancho, cy + alto, ancho, alto, 4, 2)
objeto(cx - ancho, cy + alto, ancho, alto, 3, 3)
objeto(cx - ancho, cy - alto, ancho, alto, 1, 4)
End Sub
Sub main()
Dim cx As Integer = 40, cy As Integer = 12, ancho As Integer = 8
Dim alto As Integer = 8, tipo As Integer = 1, color As Integer = 9, pasox As Integer = 4
Console.Clear()
modelo(cx, cy, ancho, alto)
Console.ReadLine()
End Sub
End Module
Sub main()
Dim cx As Integer = 40, cy As Integer = 12, ancho As Integer = 8
Dim alto As Integer = 8, tipo As Integer = 1, color As Integer = 9, pasox As Integer = 4
While (1)
If (cx <= (70 - alto)) Then
cx = cx + pasox
Else : cx = alto
End If
Console.Clear()
modelo(cx, cy, ancho, alto)
System.Threading.Thread.Sleep(10)
End While
Console.ReadLine()
End Sub
forme la figura
Programacion y métodos numéricos 2019 A\ Funciones / Ismael Véliz Vilca - 191 -
Sub main()
Dim cx As Integer = 1, cy As Integer = 6, ancho As Integer = 6, alto As Integer = 6,
fila As Integer, col As Integer
cx = alto
For fila = 1 To 2
For col = 1 To 6
modelo(cx, cy, ancho, alto)
cx = cx + 2 * alto
Next
cy = cy + 2 * alto
cx = alto
Next
Console.ReadLine()
End Sub
Sub main()
Dim x1 As Integer = 1
Dim y1 As Integer = 1
Dim x2 As Integer = 60
Dim y2 As Integer = 20
Console.ForegroundColor = 10
linea(x1, y1, x2, y2)
Console.ForegroundColor = 12
Console.SetCursorPosition(x1, y1)
Console.Write("P1")
Console.SetCursorPosition(x2, y2)
Console.Write("P2")
Console.ReadLine()
End Sub
End Module
Defina un procedimientosn llamada linea que dibuja una linea del punto1 (x1,y2) hasta
el punto2 (x2,y2) , usando esa función dibuje triángulos como en la figura mostrada
Module Module1
' poner procedimiento linea
Sub triangulo(ByVal px1 As Single, ByVal py1 As Single, ByVal px2 As Single, ByVal
py2 As Single,
ByVal px3 As Single, ByVal py3 As Single, ByVal color1 As Single,
ByVal color2 As Single)
Dim cx, cy As Integer
Console.ForegroundColor = CType(color1, ConsoleColor)
linea(px1, py1, px2, py2)
linea(px2, py2, px3, py3)
linea(px3, py3, px1, py1)
cx = CInt((px1 + px2 + px3) / 3)
cy = CInt((py1 + py2 + py3) / 3)
Console.ForegroundColor = CType(color2, ConsoleColor)
Console.SetCursorPosition(CInt(px1), CInt(py1))
Console.WriteLine("P1")
Console.SetCursorPosition(CInt(px2), CInt(py2))
Console.WriteLine("P2")
Console.SetCursorPosition(CInt(px3), CInt(py3))
Console.WriteLine("P3")
Console.SetCursorPosition(cx, cy)
Console.WriteLine("C")
End Sub
Sub main()
Console.ForegroundColor = CType(9, ConsoleColor)
Dim px1 As Integer = 1, py1 As Integer = 1, px2 As Integer = 1, py2 As Integer =
20, px3 As Integer = 40, py3 As Integer = 1
triangulo(px1, py1, px2, py2, px3, py3, 9, 10)
triangulo(2, 20, 41, 2, 60, 20, 12, 14)
triangulo(16, 18, 40, 8, 52, 18, 10, 15)
triangulo(16, 18, 40, 8, 52, 18, 10, 15)
triangulo(60, 1, 50, 8, 70, 8, 15, 11)
Console.ReadLine()
End Sub
End Module
Module Module1
Function minus(ByVal c As String) As String
Return LCase(c)
End Function
Sub main()
Dim car As String, minuscula As String
Console.Write("Ingrese cadena en Mayuscula :")
car = Console.ReadLine()
minuscula = minus(car)
Console.WriteLine("EL caracter en minuscula es {0}", minuscula)
Console.ReadLine()
End Sub
End Module
Module Module1
Function primo(ByVal n As Integer) As Boolean
Dim control As Boolean = True
Dim i As Integer
For i = 2 To n - 1
If (n Mod i = 0) Then
control = False
Exit For
End If
Next
Return control
End Function
Sub main()
Dim numeros, cont, i As Integer
Dim np As Boolean
Console.Write("ingrese un numero :")
numeros = CInt(Console.ReadLine)
cont = 1
i=1
Console.WriteLine("los primeros {0} numeros Primos son", numeros)
While (cont <= numeros)
If (primo(i) = True) Then
cont += 1
Console.Write("{0} ", i)
End If
i=i+1
End While
Console.ReadLine()
End Sub
End Module
Module Module1
Function fact(ByVal n As Integer) As Long
Dim f As Long = 1, i As Long
For i = 1 To n
f=f*i
Next
Return f
End Function
Sub main()
Dim f, n As Long
Console.Write("Ingrese un numero ")
n = CLng(Console.ReadLine)
Console.WriteLine("El factorial de {0} es {1} ", n, fact(CInt(n)))
Console.ReadLine()
End Sub
End Module
Module Module1
Function f(ByVal x As Single) As Single
Dim y As Single = x * x + 2 * x + 3
Return y
End Function
Sub main()
Dim x As Single = 2
Console.WriteLine("el valor de x ={0} i
Entrada Función Salida
y ={1} ", x, f(x))
Console.ReadLine()
End Sub X y=f(x) y
End Module
Module Module1
Function f(ByVal x As Single) As Single
Dim y As Single = x * x + 2 * x + 3
Return y
End Function
Sub main()
Dim x As Single, y As Single
For x = 1 To 10
y = f(x)
Console.WriteLine(" {0,8:f2} {1,8:F2}", x, y)
Next
Console.ReadLine()
End Sub
End Module
Tarea. 1, Encontrar los valores de cualquier función de la forma y = f(x), dado limite
inicial, limite final y incremento.
Tarea 2. Usando funciones realice las 4 operaciones (Ver problemas resuelto
C305).
Ejemplo 13.Valores de un función z= f(x,y)
Encontrar los valores de z=x2+y2
para x=2 i y=3
Entrada Función
Ejecucion
x
z=f(x,y) z
y
Module Module1
Function f(ByVal x As Single, ByVal y As Single) As Single
Dim z As Single = x * x + y * y
Return z
End Function
Sub main()
Dim x As Single = 2, y As Single = 3
Console.WriteLine("el valor de x ={0} y= {1} z= {2}", x, y, f(x, y))
Console.ReadLine()
End Sub
End Module
Sub main()
Dim x, y As Single
Dim cx As Integer = 1, cy As Integer = 1, ancho As Integer = 72, alto As Integer =
22, pasox As Integer = 8, pasoy As Integer = 2
Dim fila, col As Integer
For fila = 0 To alto Step pasoy
For col = 0 To ancho
Console.SetCursorPosition(cx + col, cy + fila)
Console.WriteLine("=")
Next
Next
For col = 0 To ancho Step pasox
For fila = 0 To alto
Console.SetCursorPosition(cx + col, cy + fila)
Console.WriteLine("|")
Next
Next
For fila = 0 To alto
For col = 0 To ancho Step pasox
Console.SetCursorPosition(cx + col, cy + fila)
Console.WriteLine("|")
Next
Next
For x = 1 To 8
Console.SetCursorPosition(CInt(cx + x * pasox + 1), cy + 1)
Console.WriteLine("{0}", x)
Next
For y = 1 To 10
Programacion y métodos numéricos 2019 A\ Funciones / Ismael Véliz Vilca - 199 -
Module Module1
Function dcoseno(ByVal dangulo As Double) As Double
Dim dtemp As Double, angulorad As Double
angulorad = Math.PI / 180.0 * dangulo
dtemp = Math.Cos(angulorad)
Return dtemp
End Function
Sub main()
Dim dangulo As Single REM angulo en grados
Console.Write("ingrese angulo en grados")
dangulo = CSng(Console.ReadLine())
Console.WriteLine("Coseno de {0} grados es {1}", dangulo, dcoseno(dangulo))
Console.ReadLine()
Console.ReadLine()
End Sub
End Module
Module Module1
Function Menu() As Integer
Dim opcion As Integer
Console.WriteLine("1.Ingresar 2.Suma 3.Resta 4.Producto 5.Division 6.Salir")
Console.Write("Ingrese Opcionn ")
opcion = CInt(Console.ReadLine)
Return opcion
End Function
Sub main()
Dim opc As Integer
opc = Menu()
Console.WriteLine("la opcion ingrresada es {0}", opc)
Console.ReadLine()
End Sub
End Module
Module Module1
Sub csalida(ByVal cadena As String)
Console.WriteLine("{0} ", UCase(cadena))
End Sub
Sub main()
Dim cadena As String
Console.Write("ingrese una cadena :")
cadena = Console.ReadLine()
csalida(cadena)
Console.ReadLine()
End Sub
End Module
Module Module1
Module Module1
Sub nveces(ByVal fila As Integer, ByVal col As Integer, ByVal n As Integer, ByVal c
As Char)
Dim i As Integer
Console.SetCursorPosition(col, fila)
For i = 1 To n
Console.Write("{0}", c)
Next
End Sub
Sub main()
nveces(1, 4, 5, Chr(65))
nveces(2, 3, 7, CChar("X"))
nveces(3, 2, 9, CChar("*"))
Console.ReadLine()
End Sub
End Module
Module Module1
Function suma(ByVal x As Integer, ByVal y As Integer) As Integer
Return x + y
End Function
Se denomina Ámbito de una variable (scope) a la parte del programa donde dicha
variable puede ser referenciada por su nombre: Una variable puede ser limitada a un
bloque a un fichero, a una función, o a una declaración de una función prototipo
1.6.12 Variable global.- existe y tiene valor desde el principio hasta el final de la
ejecución del programa.
Module Module1
Dim x As Integer = 10
Sub procedimiento()
Console.WriteLine("procedimiento valor x= {0} ", x)
End Sub
Sub main()
Dim x As Integer = 1
Console.WriteLine("Principal valor x= {0} ", x)
procedimiento()
Console.ReadLine()
End Sub
End Module
Module Module1
Function suma(Optional ByVal x As Single = 2, Optional ByVal y As Single = 3) As
Single
Return x + y
End Function
Sub main()
Dim x As Integer = 1, y As Integer = 20
Console.WriteLine("la suma por defecto es {0}", suma())
Console.WriteLine("la suma por defecto 2do argumento {0} ", suma(5))
Console.WriteLine("No tiene argumentos por defecto {0}", suma(5, 10))
Console.ReadLine()
End Sub
End Module
Ejemplo .- Pruebe el siguiente ejemplo y vea después que pasa si omite static
Module Module1
Sub suma(ByVal y As Integer)
Static x As Integer = 0
'Dim x As Integer = 0
x=x+y
Console.WriteLine("x= {0}", x)
End Sub
Sub main()
suma(3)
suma(3)
suma(4)
Console.ReadLine()
End Sub
End Module
- RECURSIVIDAD
Se dice que una función es recursiva cuando se llama así misma directa o
indirectamente
Module Module1
Function fact(ByVal n As Integer) As Integer
Dim f As Integer
If (n > 1) Then
f = n * fact(n - 1) REM parte recursiva
Else
f = 1 REM parte no recursiva
End If
Return f
End Function
Sub main()
Dim f, n As Integer
Console.Write("Ingrese un numero ")
n = CInt(Console.ReadLine())
Console.WriteLine("El factorial de ese numero es {0} ", fact(n))
Console.ReadLine()
End Sub
End Module
A b
5 * 4! 5 * 4!
4!= 4* 6 = 24 es regresando
3 * 2! 3*2!
2!=2*1= 2 es regresando
2 * 1! 2* 1!
1 es regresando
1 1
Module Module1
Sub imprimir(ByVal x As Integer)
If (x > 1) Then imprimir(x - 1)
Console.Write("{0} ", x)
End Sub
Sub main()
Dim num As Integer
Console.Write("Ingrese un Numero ")
num = CInt(Console.ReadLine())
imprimir(num)
Console.ReadLine()
End Sub
End Module
Module Module1
Sub imprimir(ByVal li As Integer, ByVal ls As Integer)
Console.Write("{0} ", li)
If (li < ls) Then imprimir(li + 1, ls)
End Sub
Sub main()
Dim li, ls As Integer
Console.WriteLine("Ingrese limite inferior y superior ")
li = CInt(Console.ReadLine())
ls = CInt(Console.ReadLine())
imprimir(li, ls)
Console.ReadLine()
End Sub
End Module
Module Module1
Function par(ByVal n As Integer) As Integer
If (n = 0) Then Return 1
Return impar(n - 1)
Programacion y métodos numéricos 2019 A\ Funciones / Ismael Véliz Vilca - 207 -
End Function
Function impar(ByVal n As Integer) As Integer
If (n = 0) Then Return 0
Return par(n - 1)
End Function
Sub main()
Dim nro As Integer = 123, res As Integer
res = impar(nro)
If (res = 0) Then
Console.WriteLine(" {0} es PAR")
Else
Console.WriteLine("{0} es impar", nro)
End If
Console.ReadLine()
End Sub
End Module
PROBLEMAS RESUELTOS
Module Module1
Function area(ByVal x As Single) As Single
Return x * x
End Function
Module Module1
Function factorial(ByVal n As Integer) As Double
Dim f As Double = 1, i As Integer
For i = 1 To n
f=f*i
Next
Return f
End Function
Sub main()
Dim n As Integer, r As Integer
Dim combi As Integer
Console.Write("ingrese n")
n = CInt(Console.ReadLine())
Console.Write("ingrese r")
r = CInt(Console.ReadLine())
combi = CInt(factorial(n) / factorial(r) * factorial(n - r))
Console.WriteLine("la combinatoria es {0} ", combi)
Console.ReadLine()
End Sub
End Module
Module Module1
Function f(ByVal x As Single) As Single
Dim y As Single
If (x <= 0) Then
y=2
Else
If (x <= 5) Then
y = CSng(2 + 0.5 * x)
Else : y = 5
End If
End If
Return y
End Function
Sub main()
Dim x As Single, y As Single
Programacion y métodos numéricos 2019 A\ Funciones / Ismael Véliz Vilca - 209 -
For x = -2 To 10
y = f(x)
Console.WriteLine("{0,8:f2} {1,8:F2} ", x, y)
Next
Console.ReadLine()
End Sub
End Module
Module Module1
Function menu() As Integer
Dim opcion As Integer
Console.WriteLine("1.Ingresar 2.Suma 3.Resta 4.Producto 5.Division 6.Salir")
Console.Write("Ingrese Opcionn ")
opcion = CInt(Console.ReadLine())
Return opcion
End Function
Function suma(ByVal x As Single, ByVal y As Single) As Single
Return x + y
End Function
Function resta(ByVal x As Single, ByVal y As Single) As Single
Return x - y
End Function
Function producto(ByVal x As Single, ByVal y As Single) As Single
Return x * y
End Function
Function division(ByVal x As Single, ByVal y As Single) As Single
Return x / y
End Function
Sub main()
Dim n1, n2 As Single
Dim salida As Boolean = False
Dim opc As Integer
Do
opc = menu()
Select Case opc
Case 1 : Console.WriteLine("Ingrese 2 numeros ")
n1 = CSng(Console.ReadLine())
n2 = CSng(Console.ReadLine())
Case 2 : Console.WriteLine("la suma es {0}", suma(n1, n2))
Case 3 : Console.WriteLine("la resta es {0}", resta(n1, n2))
Case 4 : Console.WriteLine("El producto es {0}", producto(n1, n2))
Case 5 : Console.WriteLine("La division es {0}f", division(n1, n2))
Case 6 : salida = True
Case Else : Console.WriteLine("Ingrese la opcion correcta ")
End Select
Loop While (salida = False)
Console.ReadLine()
End Sub
End Module
1.6.24 Problema C306.- Elaborar tablas de Interés para calcular el valor futuro que
se obtiene por la fórmula F= (1+i)n donde n = número de periodos i= tasa
de interés el programa debe leer la tasa de interés inicial, tasa de interés
final, la variación de la tasa y el número de periodos
Module Module1
Sub main()
Dim np, i As Integer
Dim ti1, ti2, dti, ti As Single
Console.Write("ingrese la tasa de interes inicial :")
ti1 = CSng(Console.ReadLine())
Console.Write("Ingrese la tasa de interes final :")
ti2 = CSng(Console.ReadLine())
Console.Write("Ingrese la variacion de la tasa :")
dti = CSng(Console.ReadLine())
Console.Write("Ingrese Numero de periodos :")
np = CInt(Console.ReadLine())
For ti = ti To ti2 Step dti
Console.Write("{0,7:F4}", ti)
Next
Console.WriteLine()
Console.WriteLine("=========================================== ")
Programacion y métodos numéricos 2019 A\ Funciones / Ismael Véliz Vilca - 211 -
For i = 0 To np
Console.Write("{0,6:D} ", i)
For ti = ti1 To ti2 Step dti
Console.Write("{0,7:F4}", Math.Pow(1 + ti, i))
Next
Console.WriteLine()
Next
Console.ReadLine()
End Sub
End Module
Module Module1
Sub cuadro(ByVal cx As Integer, ByVal cy As Integer, ByVal ancho As Integer, ByVal
alto As Integer)
Dim fila, col As Integer
For fila = 0 To alto - 1
For col = 0 To ancho - 1
Console.SetCursorPosition(cx + col, cy + fila)
Console.WriteLine("*")
Next
Next
End Sub
Sub main()
Randomize()
Dim x1, y1, ancho, alto, color As Integer
While (True)
x1 = CInt(1 + Int(Rnd() * 78))
y1 = CInt(1 + Int(Rnd() * 24))
ancho = CInt(1 + Int(Rnd() * (78 - x1)))
alto = CInt(1 + Int(Rnd() * (24 - y1)))
color = CInt(1 + Int(Rnd() * 15))
Console.BackgroundColor = CType(color, ConsoleColor)
Console.ForegroundColor = CType(color, ConsoleColor)
cuadro(x1, y1, ancho, alto)
System.Threading.Thread.Sleep(20)
End While
Console.ReadLine()
End Sub
End Module
Module Module1
Public Const max As Integer = 5
Function beta(ByVal n As Integer) As Integer
n=n+1
Console.WriteLine("{0} beta", n)
If (n <= max) Then alfa(n)
Return n
End Function
Function alfa(ByVal n As Integer) As Integer
n=n+1
Console.WriteLine("{0} ALFA ", n)
beta(n)
Return n
End Function
Sub main()
Dim n As Integer = 0, c As Char
Console.Write("llamar a A o B ")
c = CChar(Console.ReadLine())
If (c = "A") Then
alfa(n)
Else : beta(n)
End If
Console.ReadLine()
End Sub
End Module
Module Module1
Dim nmov As Integer = 0
Sub mover(ByVal n As Integer, ByVal a As Integer, ByVal b As Integer, ByVal c As
Integer)
REM mover n discos desde a hasta b usando como temporal c
If (n > 0) Then
mover(n - 1, a, c, b)
nmov += 1
console.writeline("mueve un disco de {0} a {0} ", a, b)
mover(n - 1, c, b, a)
End If
End Sub
Sub main()
Dim n As Integer
Console.Write("ingrese cantidad de discos a mover ")
n = CInt(Console.ReadLine())
mover(n, 1, 3, 2)
Console.WriteLine("se realizo {0} movimientos ", nmov)
Console.ReadLine()
End Sub
End Module
Module Module1
Function fibonacci(ByVal n As Integer) As Integer
If (n > 1) Then
Return fibonacci(n - 1) + fibonacci(n - 2)
Else : Return n
End If
End Function
Sub main()
Dim resultado, num As Integer
Console.Write("Ingrese un Numero ")
num = CInt(Console.ReadLine)
resultado = fibonacci(num)
Console.WriteLine("Fibonacci ({0}) es {1}", num, resultado)
Console.ReadLine()
End Sub
End Module
. X3 X5 X7
Sen(x) = x- ---- + ---- - --- + ... x en radianes
3! 5! 7!
Module Module1
Function poten(ByVal base As Single, ByVal expo As Single) As Single
Dim p As Single = base, i As Integer
For i = 1 To CInt(expo - 1)
p = p * base
Next
Return p
End Function
Function factorial(ByVal n As Integer) As Double
Dim f As Double = 1, i As Integer
For i = 1 To n
f=f*i
Next
Return f
End Function
Sub main()
Dim x As Single = 3.1416, s As Double = 0
Dim n As Integer = 12, i As Integer, signo As Integer = -1
Console.Write("Ingrese base de angulo x")
x = CSng(Console.ReadLine())
Console.Write(" Ingrese Numero de terminos")
n = CInt(Console.ReadLine())
For i = 1 To n
signo = signo * (-1)
s = s + (signo * poten(x, i * 2 - 1) / factorial(i * 2 - 1))
Next
Console.WriteLine("la suma de la serie es {0}", s)
Console.ReadLine()
End Sub
End Module
Programacion y métodos numéricos 2019 A\ Funciones / Ismael Véliz Vilca - 215 -
Module Module1
Sub horizontal(ByVal cx As Integer, ByVal cy As Integer, ByVal ancho As Integer)
If (ancho > 0) Then horizontal(cx, cy, ancho - 1)
Console.SetCursorPosition(cx + ancho, cy)
Console.WriteLine("*")
End Sub
1.6.31 Problema C313 Calcule los valores de una funcion f(x) usando solo
recursividad
Module Module1
Function f(ByVal x As Single) As Single
Return x * x
End Function
Sub valoresF(ByVal lix As Single, ByVal lsx As Single, ByVal dx As Single)
Dim y As Single
If (lsx > lix) Then valoresF(lix, lsx - dx, dx)
y = f(lsx)
Console.WriteLine("{0,8:f2} {1,8:f2} ", lsx, y)
End Sub
Sub main()
Dim lix As Single = -3, lsx As Single = 3, dx As Single = 0.5
Console.WriteLine("{0,8} {1,8}", "X", "Y")
valoresF(lix, lsx, dx)
Console.ReadLine()
End Sub
End Module
1.6.32 Problema C314 Calcule los valores de una función f(x,y) usando solo
recursividad
Programacion y métodos numéricos 2019 A\ Funciones / Ismael Véliz Vilca - 217 -
Module Module1
Function f(ByVal x As Single, ByVal y As Single) As Single
Return x + y
End Function
Sub valoresF1(ByVal lix As Single, ByVal lsx As Single, _
ByVal dx As Single, ByVal y As Single)
Dim z As Single
If (lsx > lix) Then valoresF1(lix, lsx - 1, dx, y)
z = f(lsx, y)
Console.WriteLine("{0,8:f2} {1,8:F2} {2,8:F2}", lsx, y, z)
End Sub
Module Module1
Sub invertir(ByVal n As Integer)
Dim n1 As Integer
Console.Write("{0} ", n Mod 10)
n1 = CInt(n / 10)
If (n > 10) Then invertir(n1)
End Sub
Sub main()
Dim n As Integer
Console.Write(" leer un numero ")
n = CInt(Console.ReadLine())
Console.WriteLine("el Numero invertido es ")
invertir(n)
Console.ReadLine()
End Sub
End Module
1.6.34 Problema C316. Escriba una función para encontrar el máximo divisor de 2
números
Module Module1
Function mcd(ByVal x As Integer, ByVal y As Integer) As Integer
Dim r As Integer
While (y <> 0)
r = x Mod y
x=y
y=r
End While
Return x
End Function
Sub main()
Dim n1, n2 As Integer
Console.WriteLine("ingrese 2 numeros enteros")
n1 = CInt(Console.ReadLine())
n2 = CInt(Console.ReadLine())
Console.WriteLine("el MCD es {0} ", mcd(n1, n2))
Console.ReadLine()
End Sub
End Module
Module Module1
Function mcd(ByVal a As Integer, ByVal b As Integer) As Integer
If (b = 0) Then
Return a
Else
Return mcd(b, a Mod b)
End If
End Function
Sub main()
Dim n1, n2 As Integer
Console.WriteLine("ingrese 2 numeros enteros")
n1 = CInt(Console.ReadLine())
n2 = CInt(Console.ReadLine())
Console.WriteLine("el MCD es {0} ", mcd(n1, n2))
Console.ReadLine()
End Sub
End Module
1.6.36 Problema C318 . modifique el programa línea para dibujar cubos rellenos
de colores Tarea dibujo cubos en modelo de alambre como la mostrada
Programacion y métodos numéricos 2019 A\ Funciones / Ismael Véliz Vilca - 219 -
1.6.37 Problema C319 Usando la función linea del programa anterior dibuje un
espiral creciente y en movimiento
Module Module1
Sub main()
Dim n As Single = 5.5, da As Single = 0.4, r As Single = 1, alfa As Single
Dim cx As Single = 40, cy As Single = 12, ex As Single = 2
Dim x1, y1 As Single, x2, y2 As Single
Dim cont1 = 0, cont2 As Integer = 1
While (True)
If (cont1 < 15) Then
cont1 += 1
Else
cont1 = 1
End If
cont2 = cont1
x1 = cx
y1 = cy
For alfa = 0.2 To CSng(n * 2 * Math.PI) Step da
r = CSng(alfa * 0.25)
x2 = CSng(cx + r * Math.Cos(alfa) * ex)
y2 = CSng(cy + r * Math.Sin(alfa))
If (cont2 < 15) Then
cont2 += 1
Else : cont2 = 1
End If
Console.ForegroundColor = CType(cont2, ConsoleColor)
linea(x1, y1, x2, y2)
x1 = x2
y1 = y2
Next
System.Threading.Thread.Sleep(10)
End While
Console.ReadLine()
End Sub
End Module
Module Module1
Sub diamante(ByVal cx As Integer, ByVal cy As Integer, ByVal lado As Integer)
Console.ForegroundColor = CType(14, ConsoleColor)
rombo(cx, cy, lado)
Console.ForegroundColor = CType(9, ConsoleColor)
rombo(cx, cy, lado - 1)
Console.ForegroundColor = CType(10, ConsoleColor)
rombo(cx, cy, lado - 2)
Console.ForegroundColor = CType(12, ConsoleColor)
rombo(cx, cy, lado - 3)
Console.SetCursorPosition(cx, cy)
Console.WriteLine("*")
End Sub
Sub rombo(ByVal cx As Integer, ByVal cy As Integer, ByVal lado As Integer)
linea(cx + lado, cy, cx, cy - lado)
linea(cx, cy - lado, cx - lado, cy)
linea(cx - lado, cy, cx, cy + lado)
linea(cx, cy + lado, cx + lado, cy)
End Sub
Programacion y métodos numéricos 2019 A\ Funciones / Ismael Véliz Vilca - 221 -
Sub MAIN()
Dim lado As Integer = 4, cx As Integer = lado, cy As Integer = 1, nc As Integer = 8,
col As Integer, nf As Integer = 5, fila As Integer
For fila = 1 To nf
If (fila Mod 2 = 0) Then
cx = lado * 2
Else : cx = lado
End If
For col = 1 To nc
diamante(cx + col * lado * 2, cy + fila * lado, lado)
Next
Next
Console.ReadLine()
End Sub
REM System.Threading.Thread.Sleep(vel)
End Module
.-PROBLEMAS PROPUESTOS
1 Usando funciones
a) Convertir Grados centígrados a Fahrenheit °F= 9/5*°C +32
b) Convertir Centímetros a pulgadas. 1 pulgada = 2.54 cm
c) Dólares a soles. 1 dólar = 3.5 soles
d) Convertir coordenadas rectangulares a polares
r= sqrt(x*x+y*y) y alfa=ArcTan(x/y)
e) Convertir Coordenadas polares a rectangulares x= r*cos(alfa) y= r*sin(alfa).
2 Encontrar las sumatorias de a hasta b,
3. Escribir el valor de una función que devuelva el residuo de dos números enteros
4. Escribir una función que devuelva valor máximo de 2 números
5. Escribir una función que encuentre el promedio de 3 notas considerando las dos más
altas
6. Dibuje un rombo, enladrillado, cuadriculas, y otras figuras usando funciones.
7.- Escribir un programa para producir la tabla de valores de la ecuación
Y= 2e-0.1t*Sen(0.5t) y también de función (ex -e-x)/2
8.- Calcular el valor de la serie S= k1/K!+K3/3!+K5/5!..Kn/n! n términos.
Usando para ello las funciones de factorial y potencia
9 Resuelva los problemas de la página 44 usando funciones
10. Resolver el problema de las torres de Hanoi en forma gráfica.
11. Integración por el m‚todo Simpson usando funciones;
donde Area= 1/3*dh(Y0+4y1+2y2+4y3+2Y4...+2Yn-2+4Yn-1 +Yn ).
dh= (b-a)/n a=limite inferior b:limite superior
n = Número de divisiones y debe ser par ( ver en integración numérica).
14 Encuentre una funcion que devuelva verdadero si un numero es primo y falso si no
lo es
15. usando funciones encuentre los valores de Z= X*X+Y*Y
X= 1,2,3,4,5,6 i Y=1,1; 1,2; ...1,9; 2,0
16 Encuentre los valores de la función mostrada
Y= x si 0<=x<=10
Y= sin(x) +10 si 10<x <= 20
Y= 30-x si 20<x<030
Y= 0 en lo demá casos
17 .Dibujar la siguiente figura para ello use las funciones
Lh(cx,cy,largo) Función que dibuja una línea horizontal ( a partir de la columna cx y
fila cy y un largo especificado
Lv(cx,cy,alto): Función que dibuja una línea vertical ( a partir de la columna cx y fila cy
y un alto especificado
mueve disco 2 de 2 a 3
mueve disco 1 de 1 a 3
se realizo 7 movimientos
20. se ingresa el punto inicial y la pendiente de una bola de billar simular el movimiento
de la bola, y calcular cuantas vueltas tiene que dar para llegar el mismo punto de origen
y comenzar el nuevo ciclo
EXAMENES RESUELTOS
1.6.39 Problema 1 . Dibujar cuatro casitas de menor a mayor tamaño y diferentes
colores de diferentes bordes y rellenos como se muestra en la figura
(sugerencia use la función línea hecho en clase)
Programacion y métodos numéricos 2019 A\ Funciones / Ismael Véliz Vilca - 223 -
Module Module1
Sub casa(ByVal cx As Single, ByVal cy As Single, ByVal alto As Integer, ByVal borde
As Integer, ByVal relleno As Integer)
Dim fila As Integer
Console.BackgroundColor = CType(relleno, ConsoleColor)
Console.ForegroundColor = CType(relleno, ConsoleColor)
For fila = 0 To alto
linea(cx + fila * (-1), cy + fila, cx + fila, cy + fila)
Next
For fila = 0 To alto
linea(cx - alto, cy + alto + fila, cx + alto, cy + fila + alto)
Next
Dim x1 As Single = cx
Dim y1 As Single = cy
Dim x2 As Single = CSng(cx - (alto + alto * 0.25))
Dim y2 As Single = CSng(cy + (alto + alto * 0.25))
Dim x3 As Single = CSng(cx + (alto + alto * 0.25))
Dim y3 As Single = CSng(cy + (alto + alto * 0.25))
Dim x4 As Single = cx - alto
Dim y4 As Single = cy + alto
Dim x5 As Single = cx + alto
Dim y5 As Single = y4
Dim x6 As Single = x5
Dim y6 As Single = y5 + alto
Dim x7 As Single = x4
Dim y7 As Single = y6
Console.BackgroundColor = CType(borde, ConsoleColor)
Console.ForegroundColor = CType(borde, ConsoleColor)
linea(x1, y1, x2, y2)
linea(x1, y1, x3, y3)
linea(x4, y4, x5, y5)
linea(x5, y5, x6, y6)
linea(x6, y6, x7, y7)
linea(x7, y7, x4, y4)
End Sub
Sub linea(ByVal x1 As Single, ByVal y1 As Single, ByVal x2 As Single, ByVal y2 As
Single)
Dim i As Integer, vel As Single = 10
Dim mayor, ancho, alto As Single
Dim partex, partey, px, py, dx, dy As Single
ancho = Math.Abs(x2 - x1)
alto = Math.Abs(y2 - y1)
If (x1 <= x2) Then
dx = 1
Else : dx = -1
End If
If (y1 <= y2) Then
dy = 1
Else : dy = -1
End If
If (ancho > alto) Then
mayor = ancho
Else : mayor = alto
End If
partex = ancho / mayor
partey = alto / mayor
If mayor > 0 Then
For i = 0 To CInt(mayor)
px = i * partex * dx
py = i * partey * dy
Console.SetCursorPosition(CInt(x1 + px), CInt(y1 + py))
Console.WriteLine("*")
Next
End If
End Sub
Sub MAIN()
Dim cx As Integer = 10, cy As Integer = 12, alto As Integer = 5
casa(cx, cy, alto, 12, 10)
alto += 1
cx = cx + alto * 2 + 3
cy = cy - 2
casa(cx, cy, alto, 9, 14)
alto += 1
cx = cx + alto * 2 + 3
cy = cy - 2
casa(cx, cy, alto, 9, 11)
alto += 1
cx = cx + alto * 2 + 4
cy = cy - 2
casa(cx, cy, alto, 2, 15)
Console.ReadLine()
End Sub
End Module
Programacion y métodos numéricos 2019 A\ Funciones / Ismael Véliz Vilca - 225 -
Module Module1
Function sumar(ByVal b As Integer, ByVal a As Integer) As Single
Dim s As Integer = 0
If (b > a) Then
s = CInt(b + sumar(b - 1, a))
Else : s = a
End If
Console.Write(" {0} ", s)
Return s
End Function
Sub MAIN()
Dim s, li, ls As Integer
Console.Write("ingrese limite inferior")
li = CInt(Console.ReadLine())
Console.Write("ingrese limite superior")
ls = CInt(Console.ReadLine())
s = CInt(sumar(ls, li))
Console.WriteLine("la suma es {0}", s)
Console.ReadLine()
End Sub
End Module
Module Module1
Sub arbol(ByVal cx As Integer, ByVal cy As Integer, ByVal ancho As Integer, _
ByVal alto As Integer, ByVal color1 As Integer, ByVal color2 As Integer)
Dim h, limite As Single
Dim fila, col As Integer
h = CSng(ancho / alto)
Console.ForegroundColor = CType(color1, ConsoleColor)
limite = h
For fila = 0 To alto - 1
For col = 0 To CInt(limite)
Console.SetCursorPosition(cx + col, cy + fila)
Console.WriteLine("*")
Console.SetCursorPosition(cx - col, cy + fila)
Console.WriteLine("*")
Next
limite = limite + h
Next
REM rem cuadrado
Console.ForegroundColor = CType(color2, ConsoleColor)
For fila = 0 To CInt(alto / 2)
For col = 0 To CInt(ancho / 4)
Console.SetCursorPosition(cx - col, cy + alto + fila)
Console.WriteLine("*")
Console.SetCursorPosition(cx + col, cy + alto + fila)
Console.WriteLine("*")
Next
Next
End Sub
Sub MAIN()
Dim cx As Single = 40, cy As Single = 1, alto As Single = 12
Dim ancho As Single = 16
arbol(CInt(cx), CInt(cy), CInt(ancho), CInt(alto), 10, 4)
Console.ReadLine()
End Sub
End Module
Sub MAIN()
Dim r As Integer
Randomize()
Dim cx As Integer = 12, cy As Integer = 12, alto As Integer = 8
Programacion y métodos numéricos 2019 A\ Funciones / Ismael Véliz Vilca - 227 -
Sub MAIN()
Dim cx As Single = 20, cy As Single = 2, alto As Single = 12
Dim ancho As Single = 16
Console.BackgroundColor = 9
Console.Clear()
arbol(CInt(cx), CInt(cy), CInt(ancho), CInt(alto), 10, 4)
Console.ReadLine()
End Sub
Module Module1
Sub main()
Dim c1 As Integer = 1, c2 As Integer = 32, c3 As Integer = 40, c4 As Integer = 48,
c5 As Integer = 79
Dim f1 As Integer = 1, f2 As Integer = 4, f3 As Integer = 12, f4 As Integer = 20, f5
As Integer = 23
Dim color, colorfondo As Integer
While CBool((1))
color = CInt(1 + Int(Rnd() * 15))
colorfondo = CInt(1 + Rnd() * 15)
If color >= 16 Then Continue While
colorfondo = CInt(1 + Int(Rnd() * 15))
If colorfondo >= 16 Then Continue While
Console.Clear()
Console.BackgroundColor = CType(color, ConsoleColor)
Console.ForegroundColor = CType(color, ConsoleColor)
linea(c1, f1, c1, f5)
linea(c2, f2, c2, f4)
linea(c3, f2, c3, f4)
linea(c4, f2, c4, f4)
linea(c5, f1, c5, f5)
linea(c1, f1, c5, f1)
linea(c1, f2, c5, f2)
linea(c1, f3, c5, f3)
linea(c1, f4, c5, f4)
linea(c1, f5, c5, f5)
System.Threading.Thread.Sleep(200)
End While
Console.ReadLine()
End Sub
End Module
1.6.44 4 Reconocer animal
Module Module1
Function reconoceranimal(ByVal
animal As Integer, ByVal salvaje
As Integer, ByVal caninofelino As Integer) As Integer
Dim res As Integer = 0
If animal = 1 And salvaje = 1 And caninofelino = 1 Then res = 1
If (animal = 1 And salvaje = 1 And caninofelino = 0) Then res = 2
If (animal = 1 And salvaje = 0 And caninofelino = 1) Then res = 3
If (animal = 1 And salvaje = 0 And caninofelino = 0) Then res = 4
Return res
End Function
Sub MAIN()
Dim animal As Integer = 0, salvaje As Integer = 0, caninofelino As Integer = 0,
tipoanimal As Integer = 0
Console.Write("ingrese si es animal o no 1 0 ")
animal = CInt(Console.ReadLine())
Console.Write("ingrese 1 salvaje 0 domisticado ")
salvaje = CInt(Console.ReadLine())
Console.Write("ingrese 1 canino 0 felino ")
Programacion y métodos numéricos 2019 A\ Funciones / Ismael Véliz Vilca - 229 -
caninofelino = CInt(Console.ReadLine())
tipoanimal = reconoceranimal(animal, salvaje, caninofelino)
Select Case tipoanimal
Case 1 : Console.WriteLine("LOBO")
Case 2 : Console.WriteLine("TIGRE")
Case 3 : Console.WriteLine("PERRO")
Case 4 : Console.WriteLine("GATO")
Case Else : Console.WriteLine("DESCONOCIDO")
End Select
Console.ReadLine()
End Sub
End Module
Module Module1
Sub MAIN()
Dim filtracion As Integer, admision As Integer
Console.Write("hay filtracion de combustible si 1 no 0 ")
filtracion = CInt(Console.ReadLine())
If (filtracion = 1) Then
Console.Write("hay fuga en la admision si 1 o no ")
admision = CInt(Console.ReadLine())
If (admision = 1) Then
Console.WriteLine(" REPARAR ADMISION")
Else : Console.WriteLine("CAMBIAR ADMISION")
End If
Else
Console.WriteLine("VERIFICAR CIRCUITO DE ALIMENTACION")
End If
Console.ReadLine()
End Sub
End Module
Dim cx1 As Integer = 30, cy1 As Integer = 2, color1a As Integer = 14, color1b As
Integer = 9, color1c As Integer = 12
Dim cx2 As Integer = 50, cy2 As Integer = 2, color2a As Integer = 15, color2b As
Integer = 2, color2c As Integer = 11
While CBool((1))
If (cx <= 70 - alto) Then
cx += 1
Else
cx = alto + 4
End If
barco(cx1, cy1, alto, color1a, color1b, color1c) REM barco esta atras
barco(cx, cy, alto, color1, color2, color3) REM barco actual
barco(cx2, cy2, alto, color2a, color2b, color2c) REM barco delante
System.Threading.Thread.Sleep(10)
barco(cx, cy, alto, 0, 0, 0)
End While
Console.ReadLine()
End Sub
End Module
1.6.48 Programar un algoritmo recursivo que permita hacer la división por restas
sucesivas.
Module Module1
Function division(ByVal a As Integer, ByVal b As Integer) As Integer
If (b > a) Then
Return 0
Else
Return division(a - b, b) + 1
End If
End Function
Sub main()
Dim n1 As Integer = 500, n2 As Integer = 4
Console.WriteLine("la division de {0} y {1} es {2} ", n1, n2, division(n1, n2))
Console.ReadLine()
End Sub
End Module
1.6.49 Ejercicio 5. Programar un algoritmo recursivo que permita sumar los
dígitos de un número. Ejemplo: Entrada: 123 Resultado:6
Module Module1
Function sumar_dig(ByVal n As Integer) As Integer
If (n = 0) Then REM caso base
Return n
Else
Return sumar_dig(n \ 10) + (n Mod 10)
End If
End Function
Sub main()
Dim n As Integer = 4
Console.Write("ingrese numero ")
n = CInt(Console.ReadLine())
Console.WriteLine("la suma de sus digitos es {0}", sumar_dig(n))
Console.ReadLine()
End Sub
End Module
Module Module1
Sub tabla(ByVal fila As Integer, ByVal col As Integer, ByVal nf As Integer, ByVal nc
As Integer)
Console.Write(" {0,4:D} ", fila * col)
If (col < nc) Then
tabla(fila, col + 1, nf, nc)
Else
If (fila < nf) Then
Console.WriteLine()
col = 1
tabla(fila + 1, col, nf, nc)
End If
End If
Programacion y métodos numéricos 2019 A\ Funciones / Ismael Véliz Vilca - 233 -
End Sub
Sub main()
Dim fila As Integer = 1, col As Integer = 1, nf As Integer = 12, nc As Integer = 12
tabla(fila, col, nf, nc)
Console.ReadLine()
End Sub
End Module
Module Module1
Sub cubo(ByVal cx As Integer, ByVal cy As Integer, ByVal ancho As Integer, ByVal
alto As Integer, ByVal color As Integer)
Dim p1x As Integer = cx, p1y As Integer = cy, p2x As Integer = cx, p2y As Integer
= cy + alto, p3x As Integer = cx + ancho, p3y As Integer = cy + alto, p4x As Integer = cx
+ ancho, p4y As Integer = cy
Dim p5x As Integer = CInt(cx + ancho / 2), p5y As Integer = CInt(cy - alto / 2), p6x
As Integer = CInt(cx + ancho / 2), p6y As Integer = CInt(cy + alto / 2)
Dim p7x As Integer = CInt(cx + ancho + ancho / 2), p7y As Integer = CInt(cy + alto / 2)
Dim p8x As Integer = CInt(cx + ancho + ancho / 2), p8y As Integer = CInt(cy - alto / 2)
Console.ForegroundColor = CType(color, ConsoleColor)
linea(p5x, p5y, p6x, p6y)
linea(p6x, p6y, p7x, p7y)
linea(p7x, p7y, p8x, p8y)
linea(p8x, p8y, p5x, p5y)
linea(p1x, p1y, p2x, p2y)
linea(p2x, p2y, p3x, p3y)
linea(p3x, p3y, p4x, p4y)
linea(p4x, p4y, p1x, p1y)
linea(p1x, p1y, p5x, p5y)
linea(p4x, p4y, p8x, p8y)
linea(p2x, p2y, p6x, p6y)
linea(p3x, p3y, p7x, p7y)
End Sub
Sub main()
Dim cx As Integer = 1, cy As Integer = 10, ancho As Integer = 12, alto As Integer = 8
cubo(cx, cy, ancho, alto, 14)
cubo(25, 12, 14, 10, 10)
cubo(55, 10, 10, 8, 15)
Console.ReadLine()
End Sub
End Module
Sub main()
Dim cx As Integer = 1, cy As Integer = 10, ancho As Integer = 12, alto As Integer =
8, pasox As Integer = 1
While (1)
Console.Clear()
If (cx < 70 - ancho) Then
cx = cx + pasox
Else : cx = 1
End If
cubo(cx, cy, ancho, alto, 14)
System.Threading.Thread.Sleep(10)
End While
Sub main()
Dim cx As Integer = 1, cy As Integer = 10, ancho As Integer = 12, alto As Integer =
8, pasox As Integer = 1
While (1)
Console.Clear()
If (ancho < 20) Then
ancho += 1
Else : ancho = 1
End If
alto = ancho
cubo(cx, cy, ancho, alto, 14)
System.Threading.Thread.Sleep(10)
End While
Console.ReadLine()
End Sub
1.6.52 8 dibujar el cubo rellenado
Programacion y métodos numéricos 2019 A\ Funciones / Ismael Véliz Vilca - 235 -
Module Module1
Sub cuborelleno(ByVal cx As Integer, ByVal cy As Integer, ByVal ancho As Integer,
ByVal alto As Integer, _
ByVal color1 As Integer, ByVal color2 As Integer, ByVal color3 As Integer)
Console.BackgroundColor = CType(color1, ConsoleColor)
Console.ForegroundColor = CType(color1, ConsoleColor)
For fila = 0 To alto
linea(cx, cy + fila, cx + ancho, cy + fila)
Next
Console.BackgroundColor = CType(color2, ConsoleColor)
Console.ForegroundColor = CType(color2, ConsoleColor)
For col = 0 To ancho
linea(cx + col, cy, CSng(cx + ancho / 2 + col), CSng(cy - alto / 2))
Next
Console.BackgroundColor = CType(color3, ConsoleColor)
Console.ForegroundColor = CType(color3, ConsoleColor)
For fila = 0 To alto
linea(cx + ancho, cy + fila, CSng(cx + ancho + ancho / 2), CSng(cy - alto / 2 + fila))
Next
End Sub
Sub main()
Dim cx As Integer = 1, cy As Integer = 10, ancho As Integer = 12, alto As Integer =
8, pasox As Integer = 4
cuborelleno(cx, cy, ancho, alto, 14, 12, 10)
cuborelleno(25, 10, 20, 10, 9, 10, 11)
Console.ReadLine()
End Sub
End Module
Mover el cubo
Sub main()
Dim cx As Integer = 1, cy As Integer = 10
Dim ancho As Integer = 12, alto As Integer = 8, pasox As Integer = 4
While (1)
Console.Clear()
If (cx < 70 - ancho) Then
cx = cx + pasox
Else : cx = 1
End If
cuborelleno(cx, cy, ancho, alto, 14, 12, 9)
System.Threading.Thread.Sleep(30)
End While
Console.ReadLine()
End Sub
Module Module1
Sub main()
Dim alfa As Single = 0, dx As Single, cx As Single = 40, cy As Single = 12
Dim radio As Single = 12, cx1 As Single, cy1 As Single, cx2 As Single, cy2 As
Single
Dim ex As Single = 2, ey As Single = -1, ancho As Single = 12
Dim i, color As Integer
For i = 3 To 6
dx = CSng(2 * Math.PI / i)
color = 6 + i
Console.ForegroundColor = CType(color, ConsoleColor)
For alfa = 0 To 2 * Math.PI Step dx
cx1 = CSng(cx + radio * Math.Cos(alfa) * ex)
cy1 = CSng(cy + radio * Math.Sin(alfa) * ey)
cx2 = CSng(cx + radio * Math.Cos(alfa + dx) * ex)
cy2 = CSng(cy + radio * Math.Sin(alfa + dx) * ey)
linea(cx1, cy1, cx2, cy2)
Next
Next
Console.ReadLine()
End Sub
End Module
4
5
Module Module1
Sub figura(ByVal cx As Integer, ByVal cy As Integer, ByVal color1 As Integer, ByVal
color2 As Integer)
Dim a As Char = CChar(" "), b As Char = CChar("*")
Console.BackgroundColor = 0
Console.ForegroundColor = CType(color1, ConsoleColor)
' Console.BackgroundColor = color1
Console.SetCursorPosition(cx, cy)
Console.WriteLine("{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}", a, a, b, b, b, b, b, a, a, a)
Console.SetCursorPosition(cx, cy + 1)
Console.WriteLine("{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}", a, a, b, b, b, b, b, a, a, a)
Console.SetCursorPosition(cx, cy + 2)
Console.WriteLine("{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}", b, b, b, b, b, b, b, b, b, b)
Console.SetCursorPosition(cx, cy + 3)
Console.WriteLine("{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}", b, b, b, b, b, b, b, b, b, b)
Console.ForegroundColor = CType(color2, ConsoleColor)
Console.BackgroundColor = CType(color2, ConsoleColor)
'Console.BackgroundColor = 0
Console.SetCursorPosition(cx + 1, cy + 3)
Console.WriteLine("{0}{1}", b, b)
Console.SetCursorPosition(cx + 1, cy + 4)
Console.WriteLine("{0}{1}", b, b)
Console.SetCursorPosition(cx + 7, cy + 3)
Console.WriteLine("{0}{1}", b, b)
Console.SetCursorPosition(cx + 7, cy + 4)
Console.WriteLine("{0}{1}", b, b)
End Sub
Sub main()
Dim i, color1 As Integer, color2 As Integer
While CBool((1))
color1 = CInt(1 + Int(Rnd() * 15))
color2 = 15 - color1
For i = 1 To 50
figura(i, 5, color1, color2)
'Console.ReadLine()
System.Threading.Thread.Sleep(50)
'Console.Clear()
figura(i, 5, 0, 0)
Next
End While
Console.ReadLine()
End Sub
End Module
Module Module1
Sub poligono(ByVal cx As Integer, ByVal cy As Integer, ByVal n As Integer, ByVal
valor As Single)
Dim radio As Single = 12, dalfa As Single = CSng(2 * Math.PI / n)
Dim px1, py1, alfa, px2, py2 As Single
px1 = CSng(cx + radio * Math.Cos(valor))
py1 = CSng(cy + radio * Math.Sin(valor))
For alfa = valor + dalfa To CSng(2 * Math.PI + valor + dalfa) Step dalfa
px2 = CSng(cx + radio * Math.Cos(alfa))
py2 = CSng(cy + radio * Math.Sin(alfa))
linea(px1, py1, px2, py2)
px1 = px2
py1 = py2
Next
End Sub
Sub main()
Dim cx As Integer = 20, cy As Integer = 12, n As Integer = 6, color As Integer = 9
Dim alfa As Single, dx As Single = 0.2
While CBool((1))
If (color < 15) Then
color += 1
Else : color = 9
End If
If (cx < 50) Then
cx += 1
Else : cx = 20
End If
For alfa = 0 To 2 * Math.PI Step dx
Console.ForegroundColor = CType(color, ConsoleColor)
poligono(cx, cy, n, alfa)
System.Threading.Thread.Sleep(20)
Console.ForegroundColor = 0
poligono(cx, cy, n, alfa)
cx = cx + 1
Next
End While
End Sub
End Module
TAREAS
Tarea se revisara estos ejercicios (con nota)
1. Elaborar un programa para ejecutar un juego con las siguientes características:
a) El juego consiste en disparar a un avión que pasa por la pantalla a una altura
aleatoria.
b) La batería que dispara al avión debe moverse con las teclas direccionales.
c) Se debe hacer puntaje por cada avión derribado.
d) Adicionar al programa dificultades y niveles. El avión puede también arrojar
bombas en forma aleatoria.
e) Elaborar en modo visual
nota es mas facil en modos visual
1.6.57 Se tiene una mesa de billar se ingresa el punto inicial (x1,y1) de la bola y la
pendiente , elaborar un programa que dibuje la trayectoria de la bola (
después de un cierto tiempo se estabiliza)
Module Module1
Sub main()
Dim a As Single, b As Single, dx As Single = 1
Dim x1 As Single = 1, x2 As Single = 78, y1 As Single = 1, y2 As Single = 24
Dim px1, py1, px2, py2, x As Single, y As Single
px1 = 1
py1 = 10
px2 = 24
py2 = 24
b=1
Dim i As Integer, color As Integer = 9
Dim subir As Boolean = True
Dim noerror As Boolean
While CBool((1))
noerror = True
a = py1 - b * px1
x = px1
Do
y=a+b*x
If (x >= x1 And x <= x2 And y >= y1 And y <= y2) Then
x = x + dx
If (x = x2) Then
subir = False
noerror = False
End If
If (x = x1) Then
subir = True
noerror = False
If (color < 15) Then
color += 1
Else
Programacion y métodos numéricos 2019 A\ Funciones / Ismael Véliz Vilca - 241 -
color = 9
End If
Console.ForegroundColor = CType(color, ConsoleColor)
If (subir = True) Then
dx = 1
Else : dx = -1
End If
px2 = x
py2 = y
End If
Else
noerror = False
End If
Loop While (noerror = True)
linea(px1, py1, px2, py2)
px1 = px2
py1 = py2
b = b * (-1)
End While
Console.ReadLine()
End Sub
End Module
Module Module1
Sub marco(ByVal cx As Integer, ByVal cy As Integer, ByVal ancho As Integer, ByVal
alto As Integer)
Dim fila, col As Integer
For col = 0 To ancho - 1
Console.SetCursorPosition(cx + col, cy)
Console.WriteLine("*")
Console.SetCursorPosition(cx + col, cy + alto)
Console.WriteLine("*")
Next
For fila = 0 To alto
Console.SetCursorPosition(cx, cy + fila)
Console.WriteLine("*")
Console.SetCursorPosition(cx + ancho, cy + fila)
Console.WriteLine("*")
Next fila
End Sub
Module Module1
Function f(ByVal x As Single, ByVal r As Single) As Single
Return CSng(Math.Sqrt(r * r - Math.Pow(x, 2)))
End Function
Function f1(ByVal x As Single, ByVal r As Single) As Single
Return CSng(-Math.Sqrt(r * r - Math.Pow(x, 2)))
End Function
Sub main()
Dim np As Integer = 20
Dim r As Single = 10, cx As Single = 40, cy As Single = 12, x As Single, y As
Single, y1 As Single
Dim dx As Single, ex As Single = 1, ey As Single = -1, px As Single, py As Single
dx = Math.Abs(2 * r) / np
For y = cy - r To cy + r Step dx
For x = cx - r To cx + r Step dx
If Math.Pow(x - cx, 2) + Math.Pow(y - cy, 2) <= r * r Then
Console.SetCursorPosition(CInt(x), CInt(y))
Console.Write("*")
End If
Next
Next
Console.ReadLine()
End Sub
End Module
Module Module1
Function positivo(ByVal n As Integer) As Boolean
If (n > 0) Then
Return True
Else
Return negativo(n)
End If
End Function
Function negativo(ByVal n As Integer) As Boolean
If (n < 0) Then
Return False
Else : Return positivo(n)
End If
End Function
Sub main()
Dim n As Integer = -4
Dim resultado As Boolean = positivo(n)
If (resultado = True) Then
Console.WriteLine("el numero es Positivo")
Else
Console.WriteLine("el numero es negativo ")
End If
Console.ReadLine()
End Sub
End Module
Module Module1
Function par(ByVal n As Integer) As Boolean
If (n = 0) Then
Return True
Else
Return impar(n - 1)
End If
End Function
Function impar(ByVal n As Integer) As Boolean
If (n = 0) Then
Return False
Else
Return Par(n - 1)
End If
End Function
Sub main()
Dim n As Integer = 3
Dim resultado As Boolean = par(n)
If (resultado = True) Then
Console.WriteLine("el numero es Par")
Else : Console.WriteLine("el numero es Impar ")
End If
Console.ReadLine()
End Sub
End Module
Module Module1
Dim color As Integer = 1, cont As Integer = 1, paso As Integer = 2
Sub centro(ByVal x1 As Integer, ByVal y1 As Integer, ByVal x2 As Integer, ByVal y2
As Integer)
Dim cx, cy As Integer
Dim ancho, alto As Integer
color = CInt(1 + Rnd() * 14)
cx = CInt((x1 + x2) / 2)
cy = CInt((y1 + y2) / 2)
Console.ForegroundColor = CType(color, ConsoleColor)
'Console.BackgroundColor = color
ancho = x2 - x1
alto = y2 - y1
cuadro(x1, y1, ancho, alto)
Console.SetCursorPosition(cx, cy)
Console.WriteLine("{0} ", cont)
cont = cont + 1
If (Math.Abs(x2 - x1) > 4 And Math.Abs(y2 - y1) > 4) Then
REM console.foregroundcolor(0,cont++)
centro(x1, y1, cx, cy)
centro(cx, y1, x2, cy)
centro(x1, cy, cx, y2)
centro(cx, cy, x2, y2)
End If
End Sub
Sub main()
centro(1, 1, 78, 24)
Console.ReadLine()
End Sub
End Module
1.6.63 13. elabore la siguiente aplicación usando recursividad
Module Module1
Sub lineacolores(ByVal x1 As Single, ByVal y1 As Single, ByVal x2 As Single, ByVal
y2 As Integer, ByVal fila As Single)
Dim cx, cy As Integer
cx = CInt((x1 + x2) / 2)
cy = CInt((y1 + y2) / 2)
Console.BackgroundColor = CType(12, ConsoleColor)
Console.ForegroundColor = CType(12, ConsoleColor)
linea(x1, fila, cx, fila)
Console.BackgroundColor = CType(10, ConsoleColor)
Console.ForegroundColor = CType(10, ConsoleColor)
linea(cx, fila, x2, fila)
If ((x2 - x1) > 3) Then
lineacolores(x1, y1, cx, cy, fila + 1)
lineacolores(cx, cy, x2, y2, fila + 1)
End If
End Sub
Sub main()
lineacolores(1, 1, 78, 1, 1)
Console.ReadLine()
End Sub
End Module
Module Module1
Dim fila As Integer = 1
Sub figura(ByVal cx As Integer, ByVal ancho As Integer, ByVal alto As Integer, ByVal
fila As Integer)
Console.BackgroundColor = CType(10, ConsoleColor)
Console.ForegroundColor = CType(10, ConsoleColor)
linea(cx, fila, cx, fila + alto)
Console.ForegroundColor = CType(12, ConsoleColor)
Console.BackgroundColor = CType(12, ConsoleColor)
linea(cx - ancho, fila, cx + ancho, fila)
If (ancho > 1) Then
figura(cx - ancho, CInt(ancho / 2), alto, fila - alto)
figura(cx + ancho, CInt(ancho / 2), alto, fila - alto)
End If
End Sub
Module Module1
Dim Cadena As String
Function sumacadena(CADENA As String, n As Integer, lim As Integer) As String
Dim s As String = ""
If (n <= lim) Then
s = CStr(n) + sumacadena(s, n + 1, lim) REM parte recursiva
Console.WriteLine(" {0} {1} ", n, s)
Else
s = "" REM parte no recursiva
End If
Return s
End Function
Sub main()
Dim n As Integer = 0
'Console.Write("Ingrese un numero ")
'n = CInt(Console.ReadLine())
Dim lim As Integer = 5
Console.WriteLine("LA SUMATORIA de ese numero es {0} ",
sumacadena(Cadena, n, lim))
Console.ReadLine()
End Sub
End Module
Sub MAIN()
Console.WriteLine(" la suma es {0} ", suma(10))
Console.ReadLine()
En sub
Module Module4
Function f(ByVal x As Single) As Single
Return x * x
End Function
Function Trapecialrecursivo(ap, a, b, h) As Single
Dim x, y1, y2 As Single
If a < b Then
y1 = f(a)
y2 = f(a + h)
ap = (y1 + y2) / 2 * h
Return ap + Trapecialrecursivo(ap, a + h, b, h)
Else
Return 0
End If
End Function
Function Trapecial(ByVal a As Single, ByVal b As Single, ByVal n As Integer) As
Single
Dim at As Single, ap, dx As Single
ap = 0
dx = (b - a) / n
at = Trapecialrecursivo(ap, a, b, dx)
Return at
End Function
Sub Main()
Dim a, b, area As Single
area = Trapecial(0, 2, 4000)
Console.WriteLine("La integral es {0} ", area)
Console.ReadLine()
End Sub
End Module
Programacion y métodos numéricos 2019 A\ Funciones / Ismael Véliz Vilca - 251 -
AUTO TERMINADO. La siguiente aplicación puede mover un auto con las teclas
direccionales .
Module Module1
Dim cki As ConsoleKeyInfo
Dim ax1, ay1, ax2, ay2, bx1, by1, bx2, by2 As Integer
Dim cx1, cy1, cx2, cy2, dx1, dy1, dx2, dy2 As Integer
Sub contadorMov(cx As Integer, cy As Integer, Mov As Integer)
Console.ForegroundColor = 15
Console.SetCursorPosition(30, 12)
Console.Write("Cx = {0} cy= {1} Mov ={2}", cx, cy, Mov)
End Sub
Sub main()
Cuadro(1, 1, 79, 24, 10)
Do
cki = Console.ReadKey()
mov = mov + 1
contadorMov(Px, Py, mov)
Select Case dir
Case 1 : autoderecho(Px, Py, ancho, alto, borrador, borrador, "") ' derecha
Case 2 : autoabajo(Px, Py, alto, ancho, borrador, borrador, "") ' abajo
Case 3 : autoIzquierdo(Px, Py, ancho, alto, borrador, borrador, "") 'izquierda
Case 4 : autoarriba(Px, Py, alto, ancho, borrador, borrador, "")
End Select
If cki.Key = ConsoleKey.LeftArrow Then 'flecha izquierda
Px = Px - 1
dir = 3
autoIzquierdo(Px, Py, ancho, alto, Color1, Color2, "B")
End If
If cki.Key = ConsoleKey.RightArrow Then ' derecha
Px = Px + 1
dir = 1
autoderecho(Px, Py, ancho, alto, Color1, Color2, "A")
End If
If cki.Key = ConsoleKey.UpArrow Then ' flecha arriba
Py = Py - 1
dir = 4
autoarriba(Px, Py, alto, ancho, Color1, Color2, "D")
End If
If cki.Key = ConsoleKey.DownArrow Then 'flecha abajo
Py = Py + 1
dir = 2
autoabajo(Px, Py, alto, ancho, Color1, Color2, "C")
End If
Loop While cki.Key <> ConsoleKey.Escape
Console.ReadLine()
End Sub
End Module
Module Module1
Dim radio As Single
Dim x1, y1, x2, y2, m, angulo As Single
Sub Main()
x1 = 1
y1 = 1
x2 = 10
y2 = 10
Programacion y métodos numéricos 2019 A\ Funciones / Ismael Véliz Vilca - 253 -
End Module
Un equalizador.