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
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.
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
Output to the While loop C# code.
I hope you understood how to use a While loop using C# Code.