English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
C# provides the while loop, which repeats the code block as long as the specified condition returns false.
Syntax:
while(condition) { //code block }
The while loop starts with the while keyword and must contain a boolean condition expression within brackets that returns true or false. It executes the code block until the specified condition expression returns false.
The for loop contains initialization and increment/decrement part. When using a while loop, initialization should be completed before the loop starts, and increment or decrement steps should be performed within the loop.
int i = 0; // initialization while (i < 10) //condition { Console.WriteLine("i = {0}", i); i++; // increment }
i = 0 i = 1 i = 2 i = 3 i = 4 i = 5 i = 6 i = 7 i = 8 i = 9
The above while loop contains an expression i <10. In the while loop, use i ++increase the value of i to1. When the value of i equals10and the condition i <10When false is returned, the above while loop will be executed.
Use the break or return keyword to exit the while loop under certain conditions, as shown below.
int i = 0; while (true) { Console.WriteLine("i = {0}", i); i++; if (i > 10) break; }
Ensure that the calculation result of the condition expression is false, or exit the while loop under certain conditions to avoid infinite loops. The following loop lacks appropriate conditions or breaks to exit the loop, making it an infinite while loop.
int i = 0; while (i > 0) { Console.WriteLine("i = {0}", i); i++; }
C# allows while loops to be nested within another while loop, as shown below. However, it is not recommended to use nested while loops, as they are difficult to debug and maintain.
int i = 0, j = 1; while (i < 2) { Console.WriteLine("i = {0}", i); i++; while (j < 2) { Console.WriteLine("j = {0}", j); j++; } }
i = 0 j = 1 i = 1