Algorithm


In C#, while and do...while are loop constructs that allow you to repeatedly execute a block of code as long as a specified condition is true. Here's an overview of both types of loops:

while Loop:

The while loop repeatedly executes a block of code as long as the specified condition is true. The condition is evaluated before the execution of the loop body.

 

Code Examples

#1 Code Example- while Loop in C# Programming

Code - C# Programming

using System;

namespace Loop
{
	class WhileLoop
	{
		public static void Main(string[] args)
		{
			int i=1;
			while (i < =5)
			{
				Console.WriteLine("C# For Loop: Iteration {0}", i);
				i++;
			}
		}
	}
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
C# For Loop: Iteration 1
C# For Loop: Iteration 2
C# For Loop: Iteration 3
C# For Loop: Iteration 4
C# For Loop: Iteration 5

#2 while loop to compute sum of first 5 natural numbers in C# programming

Code - C# Programming

using System;

namespace Loop
{
	class WhileLoop
	{
		public static void Main(string[] args)
		{
			int i=1, sum=0;

			while (i < =5)
			{
				sum += i;
				i++;
			}
			Console.WriteLine("Sum = {0}", sum);
		}
	}
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Sum = 15

#3 do...while loop in C# programming

Code - C# Programming

using System;

namespace Loop
{
	class DoWhileLoop
	{
		public static void Main(string[] args)
		{
			int i = 1, n = 5, product;

			do
			{
				product = n * i;
				Console.WriteLine("{0} * {1} = {2}", n, i, product);
				i++;
			} while (i  < = 10);
		}
	}
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
Advertisements

Demonstration


C# Programming while and do...while loop