Control de Flujo
## Objetivos de Aprendizaje
- Dominar instrucciones if, else if, else
- Comprender instrucciones switch
- Aprender bucles for, while, do-while
- Usar break y continue
- Dominar pattern matching
## Instrucción if
### if Básico
```csharp
int age = 18;
if (age >= 18)
{
Console.WriteLine("Adult");
}
```
### if-else
```csharp
int age = 15;
if (age >= 18)
{
Console.WriteLine("Adult");
}
else
{
Console.WriteLine("Minor");
}
```
### if-else if-else
```csharp
int score = 85;
char grade;
if (score >= 90)
{
grade = 'A';
}
else if (score >= 80)
{
grade = 'B';
}
else if (score >= 70)
{
grade = 'C';
}
else if (score >= 60)
{
grade = 'D';
}
else
{
grade = 'F';
}
Console.WriteLine("Grade: " + grade);
```
## Operador Ternario
```csharp
int age = 20;
string status = (age >= 18) ? "adult" : "minor";
```
## Instrucción switch
### switch Básico
```csharp
int day = 3;
string dayName;
switch (day)
{
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid";
break;
}
Console.WriteLine(dayName);
```
### Expresión Switch (C# 8+)
```csharp
string dayName = day switch
{
1 => "Monday",
2 => "Tuesday",
3 => "Wednesday",
4 => "Thursday",
5 => "Friday",
6 => "Saturday",
7 => "Sunday",
_ => "Invalid"
};
```
### Casos Múltiples
```csharp
switch (month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days = 31;
break;
case 4:
case 6:
case 9:
case 11:
days = 30;
break;
case 2:
days = 28;
break;
}
```
### Switch con Cláusula when
```csharp
switch (value)
{
case int i when i > 0:
Console.WriteLine("Entero positivo");
break;
case int i when i < 0:
Console.WriteLine("Entero negativo");
break;
case null:
Console.WriteLine("Null");
break;
}
```
## Pattern Matching
### Pattern is
```csharp
object obj = "Hello";
if (obj is string s)
{
Console.WriteLine($"Longitud de cadena: {s.Length}");
}
```
### Pattern Matching con switch
```csharp
string Describe(object obj) => obj switch
{
int i when i > 0 => $"Entero positivo {i}",
int i when i < 0 => $"Entero negativo {i}",
int i => $"Cero {i}",
string s => $"Cadena de longitud {s.Length}",
null => "Null",
_ => "Algo más"
};
```
## Bucle for
### for Básico
```csharp
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i); // 0, 1, 2, 3, 4
}
```
### For-Each
```csharp
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int num in numbers)
{
Console.WriteLine(num);
}
```
### Con Múltiples Variables
```csharp
for (int i = 0, j = 10; i < 5; i++, j--)
{
Console.WriteLine($"{i} - {j}");
}
```
## Bucle while
### while Básico
```csharp
int i = 0;
while (i < 5)
{
Console.WriteLine(i);
i++;
}
```
### while con Condición Primero
```csharp
string input;
while (!string.IsNullOrEmpty(input = Console.ReadLine()))
{
Console.WriteLine("Ingresaste: " + input);
}
```
## Bucle do-while
### Ejecuta al Menos Una Vez
```csharp
int i = 0;
do
{
Console.WriteLine(i);
i++;
} while (i < 5);
```
### Ejemplo de Menú
```csharp
int choice;
do
{
Console.WriteLine("1. Nuevo Juego");
Console.WriteLine("2. Cargar Juego");
Console.WriteLine("3. Salir");
Console.Write("Elige: ");
choice = int.Parse(Console.ReadLine());
} while (choice < 1 || choice > 3);
```
## break y continue
### break - Salir del Bucle
```csharp
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
break; // Sale cuando i es 5
}
Console.WriteLine(i); // 0, 1, 2, 3, 4
}
```
### continue - Saltar Iteración
```csharp
for (int i = 0; i < 5; i++)
{
if (i == 2)
{
continue; // Salta cuando i es 2
}
Console.WriteLine(i); // 0, 1, 3, 4
}
```
## Bucles Anidados
```csharp
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
Console.Write($"({i},{j}) ");
}
Console.WriteLine();
}
// Salida:
// (0,0) (0,1) (0,2)
// (1,0) (1,1) (1,2)
// (2,0) (2,1) (2,2)
```
## goto
### Instrucciones con Etiquetas
```csharp
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
if (j == 2)
{
goto End;
}
Console.WriteLine($"{i},{j}");
}
}
End:
Console.WriteLine("Done");
```
## Patrones Comunes
### Sumar 1 a N
```csharp
int sum = 0;
for (int i = 1; i <= 100; i++)
{
sum += i;
}
```
### Buscar en Arreglo
```csharp
int[] numbers = { 3, 7, 2, 9, 4 };
int target = 9;
foreach (int num in numbers)
{
if (num == target)
{
Console.WriteLine("¡Encontrado!");
break;
}
}
```
### Contar Coincidencias
```csharp
int[] numbers = { 1, 2, 3, 2, 4, 2, 5 };
int target = 2;
int count = 0;
foreach (int num in numbers)
{
if (num == target)
{
count++;
}
}
Console.WriteLine("Cantidad: " + count);
```
## Resumen
- if/else if/else para lógica condicional
- switch para múltiples valores discretos
- expresión switch para C# 8+ moderno
- Pattern matching con is y switch
- bucle for para iteraciones conocidas
- foreach para iteración de colecciones
- bucle while para iteración basada en condiciones
- do-while para iteración de al menos una vez
- break sale del bucle; continue salta la iteración
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →