How to use a while Loop Statement in C#
This tutorial describes how to use a while loop statement in C#.
A while loop is a control flow statement to execute a block of code while a specified condition evaluates to true. A while loop can execute zero or more times.
If you need to break out the loop, use the break statement.
Related tutorials:
The while Loop Syntax
The syntax of the while loop is as follows:
while (condition) { //Block of code }
Examples
Example 1
The following example shows you how to write the while loop statement to print out each value in the array:
using System; namespace WhileLoopExample { class Program { static void Main(string[] args) { string[] strings = new string[] { "D", "A", "C", "B", "E", "F" }; int i = 0; while (i < strings.Length) { Console.WriteLine(strings[i]); i++; } } } }
Output:
D A C B E F
Example 2
The following example shows you how to find the sum of numbers from 1 to 100 by using the while loop:
using System; namespace WhileLoopExample { class Program { static void Main(string[] args) { int total = 0; int i = 1; while (i <= 100) { total += i; i++; } Console.WriteLine("Total: " + total); } } }
Output:
Total: 5050
Example 3
The following example shows you how to break out the loop by using the break statement:
using System; namespace WhileLoopExample { class Program { static void Main(string[] args) { int[] numbers = new int[] { 10, 20, 60, 40, 50, 90, 70, 80, 100, 30 }; int i = 0; while (true) { Console.WriteLine(numbers[i]); if (i == numbers.Length - 5) { break; } i++; } } } }
The above sample program print out the first six numbers in the array.
Output:
10 20 60 40 50 90
Example 4
You can also use the continue statement inside a while loop, as the following code shows:
using System; namespace WhileLoopExample { class Program { static void Main(string[] args) { string[] students = new string[] { "Student A", "Student B", "Student C", "Student D", "Student E", "Student F" }; int i = 0; while (i < students.Length) { if (i < students.Length - 2) { i++; continue; } else { Console.WriteLine(students[i]); i++; } } } } }
Output:
Student E Student F
More C# tutorials:
In this tutorial, you have learned how to use a while loop statement.
A while loop is a control flow statement to execute a block of code repeatedly while a specified condition evaluates to true. A while loop can execute a block of code zero or more times. If you need to break out the loop, you can use the break statement. You can also use the continue statement inside a while loop.