C# Loops and Jump Statements Explained with Simple Code Examples

“Control the flow = control the program.” 🧠⚡

In this article, we explore how loops and jump statements work in C#. These are useful for repeating actions and controlling program flow.


🔁 Loops in C#

1️⃣ For Loop

Used when you know how many times to repeat an action.

for (int i = 0; i < 5; i++)
{
    Console.WriteLine(i); // prints 0 to 4
}

2️⃣ While Loop

Repeats as long as a condition is true.

int i = 0;
while (i < 5)
{
    Console.WriteLine(i);
    i++;
}

3️⃣ Do-While Loop

Executes at least once, then repeats while condition is true.

int i = 0;
do
{
    Console.WriteLine(i);
    i++;
} while (i < 5);

4️⃣ Foreach Loop

Used to iterate over arrays or collections.

string[] fruits = { "Apple", "Banana", "Cherry" };
foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}

⚡ Jump Statements in C#

1️⃣ Break

Exits the current loop immediately.

for (int i = 0; i < 10; i++)
{
    if (i == 5) break; // stops loop at 5
    Console.WriteLine(i);
}

2️⃣ Continue

Skips current iteration and moves to next loop iteration.

for (int i = 0; i < 5; i++)
{
    if (i == 2) continue; // skips 2
    Console.WriteLine(i); // prints 0,1,3,4
}

3️⃣ Return

Exits from a method immediately.

int Sum(int a, int b)
{
    if (a < 0) return 0; // exit method
    return a + b;
}

🎯 Key Takeaway

  • Use for when iteration count is known.
  • Use while or do-while for condition-based loops.
  • Use foreach for arrays and collections.
  • Break stops the loop, continue skips iteration.
  • Return exits a method immediately.


    C# loops and jump statements infographic showing for, while, do-while, foreach, break, continue, and return

    Learn C# loops and jump statements including for, while, do-while, foreach, break, continue, and return with simple code examples.


Post a Comment

Previous Post Next Post