C# While Loop

C# while loop, also called a conditional loop, repeatedly executes a block of statements inside the loop as long as the condition is true. The condition is only tested at the beginning of each iteration of the loop. This process repeats until the condition is false. 

C# While loop is useful when you don’t know the number of loop iterations before the loop begins and don’t need a counter variable.

C# While Loop Syntax

Begin the loop with the keyword “while”, typed with a lower-cased “w”, followed by a condition within parentheses, followed by the body of the loop. 

As with the if statement, the ‘condition’ must be a bool value or an expression that returns a bool result of true or false. Any other data type will not be accepted as a condition. 

  • While loop takes only one condition.
  • When you use a while statement, it tests the condition before the while loop begins.
  • Loop tests the condition before each iteration, which must be true to perform the next iteration. The iterations end when the condition is false.
  • Loop body executes the statements multiple times as long as the condition remains true.
  • The body can be a single statement or a block of statements surrounded by curly braces.
  • If the loop’s condition never becomes false, the loop will never end. 
  • A statement inside the loop’s body will set a Boolean flag to false during an iteration to avoid an infinite or endless loop.

C# While Loop Flowchart

C# While Loop Flowchart

The semantic of the while loop is simple: The diamond symbol represents the condition that is tested. When the loop first begins, it evaluates the condition to true or false. If the condition is true, the loop executes every statement within its body and goes back to the top to check the condition again. If the condition is still true, control returns to the top, and the whole process starts over again. This process repeats until the condition is false. In that case, C# exits the while loop and the next first statement after the loop continues. The above image shows the flowchart for the C# while statement.

The condition in a while statement may evaluate to false on the first time the loop encountered, in which case the code within the loop body never executes.

C# While Loop Example

Let’s consider a very simple example of using the while loop. When coding while loop, it’s common to use a counter variable to execute the statements in a loop a certain number of times. Here, the counter variable is an int type name i, and is assigned an initial value of 1 just before C# executes the while statement. The below code shows an example of how a C# while loop works:

int i = 1;

while (i <= 4)
{
    Console.WriteLine(i);
    i++;
}

Test Code

The last statement (i++) in the loop increments the counter with each repetition of the loop, thus increasing the counter variable value i by 1 using an increment operator (++). 

As a result, the other statement Console.WriteLine(i); in the loop body will repeatedly execute until the counter variable is less than or equal to 4. Eventually, i will become greater than or equal to 4, so the Boolean condition i <= 4 will fail and the loop will end. The while loop finishes by displaying all the numbers from 1 to 4 on the console.

OUTPUT

1
2
3
4

It’s also a common coding practice to name counter variables with single letters like i, j, and k.

C# While Loop Break

Jumping out of a loop with a break operator. C# break statement causes the while loop to end processing prematurely before it has completed the execution and passes control to the first statement immediately after the loop. A loop’s termination with a break can only be done from its body during an iteration of the loop. 

When the counter reaches 4, the condition (i == 4) evaluates to true. The break keyword then skips the code in the loop’s body and resumes execution immediately following the loop.

C# While Loop Break

Test Code

OUTPUT

Loop Counter: 1
Loop Counter: 2
Loop Counter: 3
Statement after loop.

C# While Loop Continue

Skipping to the next iteration with a continue operator. When you use C# continue statement, the loop skips to the closing brace of the while block for the current iteration and then continues with the next iteration. It passes control straight back to the start of the loop to start over.

In the below code example, the loop prints out all the numbers except one. It skips 4 due to the continue statement. When the loop hits condition (i == 4), it immediately goes back to the top and continues on with the next cycle through the loop.

C# While Loop Continue

Test Code

OUTPUT

Loop Counter: 1
Loop Counter: 2
Loop Counter: 3
Loop Counter: 5
Statement after loop.

C# While Loop Return

C# return statement will exit the current method even if used in a while loop. Normally, you’d use a break statement to exit the loop instead.

C#'s While Loop Return

Test Code

OUTPUT

Start Main() Method
  Start WhileLoop() Method
     Looping -> 1
     Looping -> 2
End Main() Method

Now remove below condition from the loop. You can see WhileLoop() method completed its execution by printing out End WhileLoop() Method.

if(i == 2)
   return;

OUTPUT

Start Main() Method
  Start WhileLoop() Method
     Looping -> 1
     Looping -> 2
     Looping -> 3
  End WhileLoop() Method
End Main() Method

Return Value Inside of While Loop in C#

This is how you can return a string or any value from the while loop in C#.

using System;

public class Program
{
    public static void Main()
    {
        Console.WriteLine(WhileLoop());
    }

    public static string WhileLoop()
    {
        int i = 0;
        while (i < 3)
        {
            i++;
            Console.WriteLine($"Looping -> {i}");

            if (i == 2)
                return $"   Loop value: {i}";
        }

        return "Any Default Value";
    }
}

Test Code

OUTPUT

Looping -> 1
Looping -> 2
  Loop value: 2

Infinite While Loop in C#

When you code while loop, it’s possible to accidentally code an infinite or endless loop, which is a loop that may never stop. If you forget to code a statement that increments the counter variable so the condition in the while loop never becomes false.

An infinite loop is rarely needed except in cases where somewhere in the loop’s body a break statement is used to end its execution prematurely.

For example, if i has a value of 4.

int i = 4;
while (i < 12)
    i -= 2;

The value of i is 4, 2, 0, -2, -4, -6, . . ., and so on. The condition, i < 12, is always true, so the loop keeps on executing until you abort the program.

int i = 0;
while (i < 5)
{
    // i++; forgot to add this
    Console.WriteLine(i);
}

Another perfectly valid example is:

while (true)
{
    Console.WriteLine("Infinite While Loop.");
}

C# Nested While Loops

A loop can contain another loop, which is called a nested loop. With each iteration of the outer loop, the inner loop fully completes all the iterations. This is how you code nested while loops:

C#'s Nested While Loop

OUTPUT

Outer -> 0
  Inner: 1
  Inner: 2
Outer -> 1
  Inner: 1
  Inner: 2
Outer -> 2
  Inner: 1
  Inner: 2

C# While Loop Multiple Conditions

For example, the following code repeats over and over until you enter a number between 1 and 10. You can put multiple conditions in the while loop using || (OR) and && (AND) operators to make it work.

int i = 1;

while (i >= 1 && i <= 10)
{
    Console.Write("Enter a number between 1 and 10: ");
    i = Int32.Parse(Console.ReadLine());
}

Console.WriteLine($"Invalid value: {i}");
Console.ReadKey();

You need to initialize i to 1, because if you had started it at 0, the flow of execution would have skipped the while loop block, and you could never choose a number.

Another way is to use the condition inside the loop’s body:

int i = 1;

while (true)
{
    Console.Write("Enter a number between 1 and 10: ");
    i = Int32.Parse(Console.ReadLine());

    if (!(i >= 1 && i <= 10))
        break;
}

Console.WriteLine($"Invalid value: {i}");
Console.ReadKey();

The following example checks whether a given number is prime or not. A prime number is any positive integer number, which is not divisible by any other number except 1 and itself like 2, 3, 5, 7, 11, 13, 17, 19, 23 and so on.

Console.Write("Enter a number: ");
int number = Int32.Parse(Console.ReadLine());

int divider = 2;
int maxDivider = (int)Math.Sqrt(number);
string primeNumber = "Yes";

while (primeNumber == "Yes" && (divider <= maxDivider))
{

    if (number % divider == 0)
        primeNumber = "No";

    divider++;
}

Console.WriteLine($"Is {number} prime number? {primeNumber}");

Test Code

C# While Loop Array

You have an integer array intArray which has 4 elements with the following values in the fixed positions in the array: 

[0] – 10
[1] – 20
[2] – 30  
[3] – 40

Let’s print out the values contained in this array using a while loop:

C#'s While Loop Array

Test Code

Above code will generate the following output:

OUTPUT

[0] = 10
[1] = 20
[2] = 30
[3] = 40

Difference Between While and Do While Loop in C#

The main difference between these two types of loops is:

Difference Between While and Do While Loop in C#

When you use a while statement, the condition (Boolean expression) is checked at the beginning before the while loop is executed. 

When you use a do-while statement, it always executes the loop body at least once in the beginning, even if the condition is false. The condition is checked when the while statement is encountered at the end.

Community Input

💬 What other C# while loop topics should I cover here?

Please use twitter or instagram to share your suggestions. We will add your feedback here.

Share With Love ❤️

Like this on Instagram

Like this on twitter

Resources

  1. while loop
  2. Break
  3. Goto
  4. Return
  5. Stackoverflow
Sending
User Rating 0 (0 vote)

TidBits