Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

C# Dictionary

  1. Home
  2. C# Dictionary
  3. while / do-while (C#)

while / do-while (C#)

The while statement repeats a block of code as long as a condition is true. The do-while statement always executes the block at least once, then evaluates the condition. In C#, use while or do-while when the number of iterations is not known in advance. The condition expression must always be of type bool.

Syntax

while (condition) {
	// Executed while the condition is true.
	// Always include logic that eventually makes the condition false, or you will get an infinite loop.
}

// Basic syntax of a do-while statement. The block runs first, then the condition is evaluated.
do {
	// Always executed at least once.
	// Repeats if the condition is true; exits if false.
} while (condition); // A semicolon is required at the end.

// Combining an infinite loop with break.
// Useful when there are multiple exit conditions inside the loop, or for service loops.
while (true) {
	// Perform some processing.
	if (exitCondition) {
		break; // Exits the loop.
	}
}

Difference between while and do-while

SyntaxWhen the condition is evaluatedMinimum executionsCommon use cases
whileBefore the block runs (pre-check)0 times (the block is skipped if the condition is false from the start).General-purpose loops with an unknown number of iterations.
do-whileAfter the block runs (post-check)1 time (the block always runs at least once, even if the condition is false).Input validation, menu selection, and other cases where at least one execution is required.

Sample code

WhileBasic.cs
using System;

class WhileBasic {
	static void Main() {

		// Repeats charging until energy reaches the target.
		int energy = 100; // Current energy.
		int target = 500; // Target energy.

		Console.WriteLine("=== Energy Charge ===");
		while (energy < target) {
			energy += 80; // Each charge increases energy by 80.
			Console.WriteLine("Charging... Current: " + energy);
		}
		Console.WriteLine("Reached target: " + target + "!");

		// Continues searching until the target item is found.
		Console.WriteLine("\n=== Searching for Target Item ===");
		string[] items = { "stone_a", "tool_b", "target_item", "part_c", "document_d" };
		int index = 0;
		while (index < items.Length) {
			Console.WriteLine("Found: " + items[index]);
			if (items[index] == "target_item") {
				Console.WriteLine("Target item secured. Search complete.");
				break; // Item found; exit the loop.
			}
			index++;
		}

		// Skips level-1 tasks and only processes higher-level ones.
		Console.WriteLine("\n=== Task Processing List ===");
		int[] taskLevels = { 4, 1, 2, 1, 3, 1, 4 }; // Level of each task.
		int i = 0;
		while (i < taskLevels.Length) {
			int grade = taskLevels[i];
			i++;
			if (grade == 1) {
				Console.WriteLine("Level 1 task skipped (out of scope).");
				continue; // Skip this iteration and move to the next.
			}
			Console.WriteLine("Level " + grade + " task processed.");
		}
	}
}

This produces the following output:

dotnet script WhileBasic.cs
=== Energy Charge ===
Charging... Current: 180
Charging... Current: 260
Charging... Current: 340
Charging... Current: 420
Charging... Current: 500
Reached target: 500!

=== Searching for Target Item ===
Found: stone_a
Found: tool_b
Found: target_item
Target item secured. Search complete.

=== Task Processing List ===
Level 4 task processed.
Level 1 task skipped (out of scope).
Level 2 task processed.
Level 1 task skipped (out of scope).
Level 3 task processed.
Level 1 task skipped (out of scope).
Level 4 task processed.
DoWhileBasic.cs
using System;

class DoWhileBasic {
	static void Main() {

		// The menu is always displayed at least once before reading input.
		// Repeats until a valid number (1-3) is entered.
		Console.WriteLine("=== Option Selection Menu ===");

		string[] options = { "option_a", "option_b", "option_c" }; // List of options.
		int choice = 0; // Selected number (initialized out of range).

		do {
			// The block always executes regardless of the condition.
			Console.WriteLine("Choose an option:");
			for (int i = 0; i < options.Length; i++) {
				Console.WriteLine("  " + (i + 1) + ": " + options[i]);
			}
			Console.Write("Enter number > ");

			// Using a fixed value here for simulation (normally read with Console.ReadLine()).
			choice = 2; // Simulating the user entering "2".
			Console.WriteLine(choice); // Display the entered value.

		} while (choice < 1 || choice > options.Length); // Repeat if the input is out of range.

		Console.WriteLine(options[choice - 1] + " selected.");

		// Accumulates energy until enough is stored for the attack.
		// The first charge always executes.
		Console.WriteLine("\n=== Energy Accumulation ===");
		int storedEnergy = 0; // Currently stored energy.
		int requiredEnergy = 300; // Energy required for the attack.
		int chargeCount = 0; // Number of charges performed.

		do {
			storedEnergy += 120; // Each charge adds 120 energy.
			chargeCount++;
			Console.WriteLine("Charge " + chargeCount + ": " + storedEnergy + " / " + requiredEnergy);
		} while (storedEnergy < requiredEnergy); // Repeat if the required energy has not been reached.

		Console.WriteLine("Ready to attack! (" + chargeCount + " charge(s) performed)");
	}
}

This produces the following output:

dotnet script DoWhileBasic.cs
=== Option Selection Menu ===
Choose an option:
  1: option_a
  2: option_b
  3: option_c
Enter number > 2
option_b selected.

=== Energy Accumulation ===
Charge 1: 120 / 300
Charge 2: 240 / 300
Charge 3: 360 / 300
Ready to attack! (3 charge(s) performed)
ServiceLoop.cs
using System;

class ServiceLoop {
	static void Main() {

		// A service loop continues processing until it receives a termination signal.
		// while(true) is effective when there are multiple exit conditions or the condition is complex.

		Console.WriteLine("=== Monitoring System Started ===");

		int tick = 0; // Number of ticks elapsed.
		bool emergency = false; // Emergency flag.

		while (true) {
			tick++;
			Console.WriteLine("[Tick " + tick + "] Scanning for threats...");

			// Simulate an emergency occurring at tick 3.
			if (tick == 3) {
				emergency = true;
				Console.WriteLine("[Warning] High-level threat detected!");
			}

			// If an emergency occurs, switch to alert mode and exit the loop.
			if (emergency) {
				Console.WriteLine("[Response] Dispatching top-level responders.");
				break; // Handle the emergency and terminate the service loop.
			}

			// Exit normally after 5 ticks with no threats.
			if (tick >= 5) {
				Console.WriteLine("[OK] No threats found. Monitoring complete.");
				break; // Normal exit from the loop.
			}
		}

		Console.WriteLine("=== Monitoring System Stopped ===");
	}
}

This produces the following output:

dotnet script ServiceLoop.cs
=== Monitoring System Started ===
[Tick 1] Scanning for threats...
[Tick 2] Scanning for threats...
[Tick 3] Scanning for threats...
[Warning] High-level threat detected!
[Response] Dispatching top-level responders.
=== Monitoring System Stopped ===

Common Mistakes

Forgetting to update the loop variable, causing an infinite loop

If the update that makes the condition false is missing from the loop body, the condition stays true forever and the loop never terminates. Pay special attention to code paths involving break or continue that might skip the update.

// NG: index is never updated, causing an infinite loop.
int index = 0;
while (index < 5) {
	Console.WriteLine(index);
	// index++; is missing.
}

Forgetting the semicolon at the end of do-while

A do-while statement requires a semicolon after } while (condition);. Omitting it causes a compile error. Since the while statement does not require a semicolon, this is an easy point to confuse.

// NG: missing semicolon causes a compile error.
// do {
//     // processing
// } while (condition)
//
// OK: add the semicolon at the end.
do {
	Console.WriteLine("processing");
} while (false); // Semicolon is required.

Notes

The while statement in C# is suited for loops where the number of iterations is not known in advance. Because the condition is evaluated before the block runs, the block is never executed if the condition is false from the start. Always include an update inside the loop that will eventually make the condition false. Forgetting this update will cause an infinite loop.

The do-while statement is a post-check loop. Because the block always runs before the condition is evaluated, at least one execution is guaranteed. It is well-suited for patterns such as input validation and menu selection, where you need to run the block first and then decide whether to continue. Note that a semicolon is required after } while (condition);.

An infinite loop with while (true) is an effective pattern for situations that have multiple explicit exit conditions, such as a game's main loop or a background service. In these cases, always make sure there is a break path that exits the loop. For loops with a known number of iterations, the for statement is more appropriate (see for statement). If you simply need to process every element of a collection in order, foreach is the simplest choice.

If you find any errors or copyright issues, please .