C# While Loop

Welcome to The Coding College! In this tutorial, we’ll explore the while loop in C#. The while loop is one of the fundamental control structures in programming that allows you to execute a block of code repeatedly based on a condition.

By the end of this guide, you will:

  • Understand the concept of a while loop.
  • Learn the syntax and structure of a while loop.
  • Practice with examples to see how the loop works.

Let’s get started! 🚀

What is a While Loop?

A while loop in C# allows you to repeatedly execute a block of code as long as the specified condition is true. It checks the condition before each iteration, and if the condition becomes false, the loop stops executing.

Syntax of While Loop

Here’s the basic syntax of a while loop in C#:

while (condition)
{
    // Code to be executed repeatedly
}

How It Works:

  1. The condition is evaluated.
  2. If the condition is true, the code block inside the while loop executes.
  3. After the block executes, the condition is checked again.
  4. This process continues until the condition becomes false.

Example 1: Basic While Loop

Let’s see a simple example of a while loop that prints numbers from 1 to 5.

using System;

class Program
{
    static void Main()
    {
        int i = 1;

        while (i <= 5)
        {
            Console.WriteLine("Number: " + i);
            i++;
        }
    }
}

Output:

Number: 1  
Number: 2  
Number: 3  
Number: 4  
Number: 5 

Explanation:

  1. We initialize i with 1.
  2. The while loop checks if i <= 5.
  3. If true, it executes the code inside and increments i using i++.
  4. This continues until i becomes 6, at which point the condition becomes false, and the loop stops.

Example 2: Infinite While Loop

If you forget to update the condition or use a stopping condition, the loop can run infinitely.

using System;

class Program
{
    static void Main()
    {
        int i = 1;

        while (true) // Infinite loop
        {
            Console.WriteLine("This is an infinite loop. Count: " + i);
            i++;
            
            // Stop the loop after 5 iterations
            if (i > 5)
            {
                break;
            }
        }
    }
}

Output:

This is an infinite loop. Count: 1  
This is an infinite loop. Count: 2  
This is an infinite loop. Count: 3  
This is an infinite loop. Count: 4  
This is an infinite loop. Count: 5 

Explanation:

  • while (true) creates an infinite loop.
  • The break statement is used to exit the loop when i > 5.

Example 3: While Loop with User Input

Let’s use a while loop to repeatedly ask for a number until the user enters 0.

using System;

class Program
{
    static void Main()
    {
        int number;

        Console.WriteLine("Enter numbers (0 to exit):");
        number = Convert.ToInt32(Console.ReadLine());

        while (number != 0)
        {
            Console.WriteLine("You entered: " + number);
            number = Convert.ToInt32(Console.ReadLine());
        }

        Console.WriteLine("Program exited.");
    }
}

Output:

Enter numbers (0 to exit):  
5  
You entered: 5  
3  
You entered: 3  
0  
Program exited.

Explanation:

  • The loop runs until the user enters 0.
  • It continuously takes input and prints it back to the user.

Example 4: Sum of Natural Numbers Using While Loop

Here’s an example to calculate the sum of the first n natural numbers.

using System;

class Program
{
    static void Main()
    {
        int n = 5; // Sum up to 5
        int i = 1;
        int sum = 0;

        while (i <= n)
        {
            sum += i;
            i++;
        }

        Console.WriteLine("Sum of first " + n + " natural numbers is: " + sum);
    }
}

Output:

Sum of first 5 natural numbers is: 15

Explanation:

  • The while loop adds each value of i (from 1 to 5) to the sum.
  • The loop stops when i becomes greater than 5.

Difference Between While Loop and For Loop

FeatureWhile LoopFor Loop
InitializationOutside the loopInside the loop header
Condition CheckAt the start of each iterationAt the start of each iteration
Use CaseWhen the number of iterations is unknownWhen the number of iterations is known

Best Practices for Using While Loops

  1. Avoid Infinite Loops: Always ensure the condition eventually becomes false to avoid infinite loops.
  2. Update Condition Variables: Update the loop control variable inside the loop to make progress.
  3. Use Break Statements: Use break to exit a loop if a certain condition is met.
  4. Clear Logic: Use while loops when the number of iterations isn’t known in advance.

Conclusion

The while loop in C# is a powerful control structure for situations where you need to repeat code based on a condition. Whether it’s taking user input, processing data, or handling unknown iterations, the while loop helps you write efficient and clean code.

For more tutorials, examples, and tips on C# programming, visit The Coding College—your ultimate destination for coding knowledge.

Leave a Comment