C# While Loop Tutorial | Learn With Examples

C# While Loop Tutorial | Learn With Examples

🔄 C# While Loop

The while loop in C# repeatedly executes a block of code as long as a specified condition is true. It's useful when you don’t know beforehand how many times the loop will run.

📘 Syntax


while (condition)
{
    // code to execute
}
  

💡 How It Works

  • The condition is evaluated before each iteration.
  • If condition is true, the loop body runs.
  • The process repeats until the condition becomes false.

📄 C# Example: While Loop


using System;

class Program
{
    static void Main()
    {
        int count = 1;
        while (count <= 5)
        {
            Console.WriteLine($"Count is: {count}");
            count++;
        }
    }
}
    

📝 Sample Output

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5

📌 Summary

  • The while loop checks the condition first before running.
  • If the condition starts false, the loop body won’t execute even once.
  • Use while loops for situations where the number of iterations is not fixed.

Post a Comment

Post a Comment (0)

Previous Post Next Post

ads

ads

Update cookies preferences