clase13 ejercicios estructurarepetitivafor
Post on 11-Jan-2017
17 Views
Preview:
TRANSCRIPT
Ejercicios Estructura repetitiva
for
Edisson Gutiérrez Jiménez
Universidad de Antioquia
Lógica y representación I
Sintaxis de la estructura de repetición
for en java
⁞ for (var = valorInicial; var <= valorFinal; var = var+paso)
{
% Bloque de Instrucciones
}
⁞
Ejemplo 1: Algoritmo para calcular el
factorial de un número ingresado por
el usuarioPROGRAMA
int i, num, facto = 1;
Scanner sc = new Scanner( System.in );
System.out.print("Ingrese el número al que desea encontrarle el factorial: ");
num = sc.nextInt();
for (i = 1; i <= num; i++)
{
facto *= i;
}
System.out.println(“El factorial de " + num + " es "+ facto);
Ejemplo 2: Prueba de escritorio para el
algoritmo del ejemplo 1
num i facto
4 1 1
2 1
3 2
4 6
5 24
Ejercicio 1: ¿Qué hace el siguiente
programa?.
PROGRAMA
int i, x, tope, y, z;
Scanner sc = new Scanner( System.in );
System.out.print(“Ingrese el total de datos: ");
tope = sc.nextInt();
x = 0;
for (i = 1; i<= tope; i++)
{
System.out.print("Ingrese un número ");
z = sc.nextInt();
x += z;
}
y = x / tope;
System.out.println(“Los resultados son " + x + " y "+ y);
top related