C# Basics

C# while loop

Table of Contents

The while Loop

C# while 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 it begins and doesn’t need a counter variable.

Here’s what you’ll cover in this tutorial:

  • You’ll start with the C# while loop syntax and execution order used for indefinite iteration (executes until some condition is met)
  • Break out of a loop or loop iteration prematurely
  • Skip and start next iteration without jumping out of the loop
  • Explore infinite and nested while loops
  • Finally, you will learn the use of while loop with array

When you’re finished, you should have a good understanding of how to use indefinite iteration in C#.

Edit, and test all the CODE examples used in this article with C# online editor:  Code Playground

Syntax

C# While Loop

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

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 (Boolean expression).
  • 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.
  • The 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.

Flowchart

C#'s While Loop Flowchart

The semantic of the C# while loop is simple: The diamond symbol represents the tested condition. 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++;
}

The last statement (i++) in the loop increments the counter with each repetition of the loop, 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.


The break Keyword With while Loop

The break Keyword With while Loop

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.

The break Keyword With while Loop Code Example

OUTPUT

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


The continue Keyword With while Loop

The continue Keyword With while Loop

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.

The continue Keyword With while Loop Code Example

OUTPUT

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


The return Keyword With while Loop

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.

The return Keyword With while Loop Code Example

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

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";
    }
}

OUTPUT

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


Infinite while Loop

When you code C# 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.");
}

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:

Nested while Loops Code Example

OUTPUT

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


Multiple Conditions With while Loop

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}");

Array With while Loop

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:

Array With while Loop Code Example

Above code will generate the following output:

OUTPUT

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


Difference Between while Loop and do-while Loop

The main difference between these two types of loops is:

Difference Between while Loop and do-while Loop

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.