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 true,
    • A statement inside the while loop executed.
    • After execution, the test-expression is evaluated again.
  • If the test-expression is evaluated to false, the while loop terminates. 
While Loop Flowchart
 
While Loop In C# Code
 

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 in C# Visual Studio.
 
While Loop In C# Code
 
This code sample shows that I will use a while loop in C# code.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. namespace while_loop {  
  7.     class Program {  
  8.         static void Main(string[] args) {  
  9.             int number = 0;  
  10.             int target = 100;  
  11.             while (number < 100) {  
  12.                 Console.WriteLine(number);  
  13.                 number++;  
  14.             }  
  15.         }  
  16.     }  
  17. }   
Save the program.
 
Now run the while loop C# code.
 
Click on the start button and debug the program
 
While Loop In C# Code
 
Output to the While loop C# code.
 
While Loop In C# Code
 
I hope you understood how to use a While loop using C# Code.