Ejercicio
Break Y Continuar
Objectivo
Cree un programa en C# para escribir los números pares del 10 al 20, ambos incluidos, excepto el 16, de 3 maneras diferentes:
- Incremento de 2 en cada paso (use "continuar" para omitir 16)
- Incrementando 1 en cada paso (use "continuar")
- Con y bucle sin fin (usando "break" y "continue")
Ejemplo Ejercicio C#
Mostrar Código C#
using System; // Importing the System namespace to use Console functionalities
class Program
{
// Main method where the program execution begins
static void Main()
{
// First method: Incrementing by 2 and using "continue" to skip 16
Console.WriteLine("Method 1: Incrementing by 2 and skipping 16");
for (int i = 10; i <= 20; i += 2) // Loop increments by 2 starting from 10
{
if (i == 16) // If the number is 16, skip it
{
continue;
}
Console.WriteLine(i); // Display the current number
}
Console.WriteLine(); // Empty line for separation between methods
// Second method: Incrementing by 1 and using "continue" to skip 16
Console.WriteLine("Method 2: Incrementing by 1 and skipping 16");
for (int i = 10; i <= 20; i++) // Loop increments by 1
{
if (i % 2 == 0 && i != 16) // Only print even numbers and skip 16
{
Console.WriteLine(i); // Display the current number
}
}
Console.WriteLine(); // Empty line for separation between methods
// Third method: Using an endless loop with "break" and "continue"
Console.WriteLine("Method 3: Endless loop with 'break' and 'continue'");
int number = 10;
while (true) // Endless loop
{
if (number > 20) // Break the loop when the number exceeds 20
{
break;
}
if (number == 16) // Skip 16
{
number++;
continue;
}
if (number % 2 == 0) // Print only even numbers
{
Console.WriteLine(number); // Display the current number
}
number++; // Increment the number
}
}
}
Salida
Method 1: Incrementing by 2 and skipping 16
10
12
14
18
20
Method 2: Incrementing by 1 and skipping 16
10
12
14
18
20
Method 3: Endless loop with 'break' and 'continue'
10
12
14
18
20
Código de Ejemplo Copiado!
Comparte este Ejercicio C# Sharp