Exercise
Break & Continue
Objective
Write a C# program to write the even numbers from 10 to 20, both inclusive, except 16, in 3 different ways:
Incrementing 2 in each step (use "continue" to skip 16)
Incrementing 1 in each step (use "continue" to skip 16)
With an endless loop (using "break" and "continue")
Write Your C# Exercise
C# Exercise Example
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
}
}
}