Skip to main content

How to Leave Out the Condition of a for Loop in C#

· 8 min read
Jagdish Kumawat
Founder @ Dewiride

for (int number = 1; ; number++) counts 1, 2, 3 and so on with nothing between the two semicolons, so the loop never stops on its own. The body decides when it's done, with break, with return, or with an exception that leaves the loop.

A for loop has three sections in its parentheses: a start, a condition and a step. Usually the condition ends the loop, as in i < 3. But you may not know the last round before the loop starts, such as the first number that passes a test, or the try that finally works. Then leave the condition out. The C# reference on the condition section: If it evaluates to true or isn't present, the next iteration runs. Otherwise, the loop exits. And on leaving: At any point within the body of an iteration statement, you can exit the loop by using the break statement.

Syntax​

Syntax
for (int <counter> = <start>; ; <counter>++)
{
<statements>

if (<done>)
{
break;
}
}
PartWhat it is
int <counter> = <start>The initializer. It runs once, before the first round
; ;Both semicolons stay. The empty space between them is the condition that's left out
<counter>++The iterator. It runs after every round, so the counter counts up
if (<done>) break;The way out. break leaves the loop, return leaves the loop and the method, and an exception that isn't caught inside the loop leaves it too

The Example​

A console app called ForWithoutCondition counts 1, 2, 3 and so on, squaring each number, and stops at the first square over 50. Then a method finds the first multiple of 7 after 100, and leaves its loop with return.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n ForWithoutCondition
cd ForWithoutCondition
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/ForWithoutCondition/ForWithoutCondition.csproj:
Determining projects to restore...
Restored /Users/you/source/ForWithoutCondition/ForWithoutCondition.csproj (in 43 ms).
Restore succeeded.

dotnet new console -n ForWithoutCondition creates a folder named ForWithoutCondition with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or ForWithoutCondition.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First, a loop that ends with break:

Program.cs (a loop that ends with break)
// Nothing between the two semicolons: the loop has no condition, so break ends it.
for (int number = 1; ; number++)
{
int square = number * number;
Console.WriteLine($"{number} x {number} = {square}");

if (square > 50)
{
Console.WriteLine($"{number} is the first number whose square is over 50.");
break;
}
}

for (int number = 1; ; number++) starts number at 1 and adds 1 after each round, but nothing between the semicolons checks it. The if inside does that job: once the square is over 50, it prints the answer, and break leaves the loop.

Then a loop that ends with return:

Program.cs (a loop that ends with return)
// In a method, return ends the loop and the method at the same time.
Console.WriteLine($"The first multiple of 7 after 100 is {FirstMultipleAfter(7, 100)}.");

static int FirstMultipleAfter(int divisor, int start)
{
for (int candidate = start + 1; ; candidate++)
{
if (candidate % divisor == 0)
{
return candidate;
}
}
}

FirstMultipleAfter tries 101, 102, 103 and so on. % gives the remainder of a division, so candidate % divisor == 0 is true for a multiple of 7. return candidate ends the loop and the method together, and hands the number back.

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
1 x 1 = 1
2 x 2 = 4
3 x 3 = 9
4 x 4 = 16
5 x 5 = 25
6 x 6 = 36
7 x 7 = 49
8 x 8 = 64
8 is the first number whose square is over 50.
The first multiple of 7 after 100 is 105.

macOS-style terminal window titled Terminal — ForWithoutCondition showing dotnet run printing the squares from 1 x 1 = 1 to 8 x 8 = 64, then 8 is the first number whose square is over 50 and The first multiple of 7 after 100 is 105

The first loop ran eight rounds. At 8 the square, 64, was over 50 for the first time, so break ran and the loop never reached 9. The second loop returned 105, the first multiple of 7 after 100.

The Complete File​

macOS-style code window titled Program.cs — ForWithoutCondition showing a for loop with no condition that squares number and breaks when the square is over 50, a line that prints FirstMultipleAfter of 7 and 100, and the FirstMultipleAfter method whose for loop with no condition returns the first candidate that divides by the divisor

Program.cs
// Nothing between the two semicolons: the loop has no condition, so break ends it.
for (int number = 1; ; number++)
{
int square = number * number;
Console.WriteLine($"{number} x {number} = {square}");

if (square > 50)
{
Console.WriteLine($"{number} is the first number whose square is over 50.");
break;
}
}

// In a method, return ends the loop and the method at the same time.
Console.WriteLine($"The first multiple of 7 after 100 is {FirstMultipleAfter(7, 100)}.");

static int FirstMultipleAfter(int divisor, int start)
{
for (int candidate = start + 1; ; candidate++)
{
if (candidate % divisor == 0)
{
return candidate;
}
}
}

A Retry Loop​

A loop with no condition suits retries: try, and try again until it works or you give up. In this second example, Download stands in for a real download: it fails a set number of times with a TimeoutException, and the loop allows three tries. The first call fails twice and then works. The second fails every time:

A retry loop
// The first two tries fail, and the third works.
Console.WriteLine(Download(failures: 2));

// Every try fails: after the third, the exception leaves the loop.
try
{
Console.WriteLine(Download(failures: 5));
}
catch (TimeoutException error)
{
Console.WriteLine($"Gave up: {error.Message}");
}

static string Download(int failures)
{
for (int attempt = 1; ; attempt++)
{
try
{
if (attempt <= failures)
{
throw new TimeoutException($"attempt {attempt} timed out");
}
return $"Downloaded on attempt {attempt}";
}
catch (TimeoutException error) when (attempt < 3)
{
Console.WriteLine($"{error.Message}, trying again");
}
}
}
Output
attempt 1 timed out, trying again
attempt 2 timed out, trying again
Downloaded on attempt 3
attempt 1 timed out, trying again
attempt 2 timed out, trying again
Gave up: attempt 3 timed out

return ended the loop when a try worked: the first call printed Downloaded on attempt 3. The catch caught a failed try only while attempt < 3 was true. The when reference: Use the when keyword in a catch clause to specify a condition that must be true for the handler for a specific exception to execute. On the third try of the second call, the condition was false, so the exception wasn't caught inside the loop. It left the loop and the method, and the catch around the call printed Gave up: attempt 3 timed out.

Common Mistakes​

MistakeWhat happensDo this instead
Forgetting the break or returnNothing ends the loop. The build warned warning CS0162: Unreachable code detected on the line after it, because the loop can't finishGive the body a way out, as in the example
Reading the counter after the looperror CS0103: The name 'number' does not exist in the current context. The reference: You can't access the declared variable from outside the for statement.Declare it before the loop, int number;, and start with for (number = 1; ; number++). A check then printed Stopped at 8
Leaving out one of the semicolons too, as in for (int number = 1; number++)error CS1002: ; expectedKeep both: for (int number = 1; ; number++)

FAQ​

Why doesn't FirstMultipleAfter need a return after its loop?​

Because without a condition, the only way out of that loop is the return inside it, and the compiler knows it. With the condition candidate < 1000 added, the build failed with error CS0161: 'FirstMultipleAfter(int, int)': not all code paths return a value: a loop with a condition can end without finding a multiple.

Does the step run after break?​

No. break leaves at once, so number++ doesn't run again. With number declared before the loop, a check printed Stopped at 8, the round that broke out, and not 9.

Conclusion​

Leave the condition out of a for loop, as in for (int number = 1; ; number++), when only the body can tell that the work is done. Keep both semicolons, and give the body a way out: break leaves the loop, return leaves the method too, and an exception that isn't caught inside the loop leaves it as well.

Additional Resources​