while Loop
A while loop is similar to a for loop, however, it is used when we need to execute a block of code repeatedly based on a condition. The syntax of a while loop is simpler than that of a for loop:
while (condition) {
// code to execute
}
Let's consider the practical example:
main.cs
12345678910111213141516using System; namespace ConsoleApp { internal class Program { static void Main(string[] args) { int i = 0; while(i < 5) { Console.WriteLine(i); i++; } } } }
Although the while loop may seem very similar to the for loop at first, In more advanced levels of programming the difference becomes apparent. We might explore the usage of different kinds of loops in the Arrays section.
Note
We can write
trueas the condition of a while-loop to create an infinite loop. But it's not recommended to use.
main.cs
123while(true) { Console.WriteLine("Hello World"); }
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Can you explain the difference between a while loop and a for loop in more detail?
Can you show a practical example of using a while loop in C#?
What happens if the condition in a while loop is always true?
Awesome!
Completion rate improved to 1.59
while Loop
Swipe to show menu
A while loop is similar to a for loop, however, it is used when we need to execute a block of code repeatedly based on a condition. The syntax of a while loop is simpler than that of a for loop:
while (condition) {
// code to execute
}
Let's consider the practical example:
main.cs
12345678910111213141516using System; namespace ConsoleApp { internal class Program { static void Main(string[] args) { int i = 0; while(i < 5) { Console.WriteLine(i); i++; } } } }
Although the while loop may seem very similar to the for loop at first, In more advanced levels of programming the difference becomes apparent. We might explore the usage of different kinds of loops in the Arrays section.
Note
We can write
trueas the condition of a while-loop to create an infinite loop. But it's not recommended to use.
main.cs
123while(true) { Console.WriteLine("Hello World"); }
Thanks for your feedback!