In the previous C# tutorial, we have discussed C# for loop with examples . In this lesson, we are going to learn C# while loop. The loop is a repetitively process to execute the same code.
Let's discuss C# while loop.
In the C# while loop, the statement executes repetitively as long as expression is true. In the C# for loop, we define the initial value, condition and increment value but in C# while loop, we specify the condition with while keyword inside the parenthesis.
In simple words, A while loop executes the statement until the condition is true. The compiler checks the condition first and execute the code of the block. In C# while loop, when the condition evaluates to false, compiler exit from the loop.
while (condition)
{
statements to be executed;
}
In the above syntax, condition to be created first and execute the block of statements as long as the condition is true.
Example of C# while loop -
Let's create an example to print the year with while loop using C# programming.
using System;
namespace whileLoop{
public class Program {
public static void Main(string[] args) {
int i=2021;
while (i>1994){
i--;
Console.WriteLine(i);
}
Console.ReadLine();
}
}
}
Output -
2020 2019 2018 2017 2016 2015 2014 2013 2012 2011 2010 2009 2008 2007 2006 2005 2004 2003 2002 2001 2000 1999 1998 1997 1996 1995 1994
In the above example, we declared a variable with its value. We created a condition and decrement the value using -- decrement operator in C#. First of all, the compiler checks the condition first and execute the block of code.