Learn while loop in C# programming with program examples and explanation with special notes. Demonstration of infinite while loop is included that run for ever.

Topics

  • Syntax of while loop with code example
  • Special note – semi colon after while ();{}
  • Infinite while loop

Syntax of a while loop in C#:

while (Your Boolean expression – also called while condition) 
{
	// Code block
	// do something
}

In while condition, if Boolean expression evaluates to true, then
code block (under body of the while loop demonstrated by opening {and closing bracket} inside the loop will be executed.

Again, control goes back to start of the loop. Again, evaluate Boolean expression in while condition. if that is true, then run the same code block again.
Once the Boolean expression evaluate to false, the control will exit the loop and don’t go inside the while loop.

C# Code Example:

Print number from 1 to 10.

public class Sample
    {

        public static void Main(String[] args) {
 
		int n = 1;
		while (n <= 10) 
		{

            Console.WriteLine(n);
			++n;
		}
 
	}
    }

Output:
1
2
3
4
5
6
7
8
9
10

SPECIAL NOTE

Be careful with semi column [; ] after while () but before body. for example, while(n<1=10);{} as it may leads to application hang.

Details:

Consider below code example,

If you put semi column after while but before its body e.g. while(n<1=10);{} then control will run while (n <= 10); forever. As, while (n <= 10); becomes a statement.

The control will always find the expression true as its value is not getting increment and always be n =1.

 public class Sample
    {

        public static void Main(String[] args) {
 
		int n = 1;
		while (n <= 10); 
		{

            Console.WriteLine(n);
			++n;
		}
 
	}
    }

 

Infinite while loop in C#

To run a while loop infinitely, just we need to write true in while condition e.g. while(true){…}.

 public class Sample
    {

        public static void Main(String[] args) {
 
		while (true) {

            Console.WriteLine("I am running infinitely...");
 
		}
 
	}
    }

Related Posts