While Loop In C#

Introduction

In this blog, we will write a C# program for the While loop.

How does a While Loop Work?

  • A C# while loop consists of a test expression.
  • If the test expression is evaluated to be true,
    • A statement inside the while loop is executed.
    • After execution, the test expression is evaluated again.
  • If the test expression is evaluated as false, the while loop terminates.

While Loop Flowchart

Loop Flowchart

While Loop

The while loop is basically a programming structure that allows us to loop over a specific block of code while a certain condition is true. Basically, by using while loops, we're able to keep doing something repeatedly while a condition is true and this comes in handy in a bunch of situations. Loops are extremely useful in a programming language like C#, so let's get started.

The project is in C# Visual Studio.

 Visual Studio

This code sample shows that I will use a while loop in C# code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace while_loop {
    class Program {
        static void Main(string[] args) {
            int number = 0;
            int target = 100;
            while (number < 100) {
                Console.WriteLine(number);
                number++;
            }
        }
    }
}

Save the program.

Now run the while loop C# code.

Click on the start button and debug the program.

Debug the program

Output to the While loop C# code.

Loop C# code

I hope you understand how to use a While loop using C# Code.

Next Recommended Reading Looping Statements in C#