Home Basics C# while loop

C# while loop

The while loop has the same syntax as in other languages derived from C. It is written in the following form:

while-loop ::= “while” “(” condition “)” body
condition ::= boolean-expression
body ::= statement-or-statement-block

The while loop evaluates its condition to determine whether to run its body. If the condition is true, the body executes. If the condition then evaluates to true again, the body executes again. When the condition evaluates to false, the while loop ends.

Syntax

while (condition) 
{
// Statements to Execute
}

A while loop consists of a condition.
If the condition is evaluated to true,
statements inside the while loop are executed.
after execution, the condition is evaluated again.
If the condition is evaluated to false, the while loop terminates.

Example

Here is an example of this

using System;

public class Program
{
	public static void Main()
	{
		int i=1;    
		while(i<=10)   
		{  
			Console.WriteLine(i);  
			i++;  
		}    
	}
}

when you run this, you will see something like this

1
2
3
4
5
6
7
8
9
10

the break statement

You can exit or terminate the execution of a while loop immediately by using a break keyword. Here is an example

using System;

public class Program
{
	public static void Main()
	{
		int i=1;    
		while(i<=10)   
		{  
			Console.WriteLine(i);  
			i++;  
			if (i == 5)
                break;
		} 
		Console.WriteLine("Press Enter Key to Exit..");
        Console.ReadLine();
	}
}

When you run this you will see something like this

1
2
3
4
Press Enter Key to Exit..

nested while loop

 

using System;

public class Program
{
	public static void Main()
	{
		int i = 1;
		while (i < 4)
		{
			Console.WriteLine("i value: {0}", i);
			i++;
			int j = 1;
			while (j < 3) 
			{
				Console.WriteLine("j value: {0}", j);
				j++;
			}
		}
		Console.WriteLine("Press Enter Key to Exit..");
		Console.ReadLine();
	}
}

You will something like this

i value: 1
j value: 1
j value: 2
i value: 2
j value: 1
j value: 2
i value: 3
j value: 1
j value: 2
Press Enter Key to Exit..

You may also like