c# do while ( Two condition ) - c#

im trying to do a loop when either one of the two conditions are met for ten times..
This involves a box of bottles either Sugar or Salt where the person must pick randomly two bottles. He/She will stop picking when it was choosen 10 times... It doesnt seem to work.
int sugar = 0;
int salt = 0;
do
bottle1.choose
bottle2.choose
{
if ((bottle1 = 'Sugar') && (bottle2 = 'Sugar'))
{
Console.Write("Sugar");
Sugar++;
}
else if (bottle1 = 'Salt') && bottle1 = 'Salt')
{
Salt++;
Console.Write("Salt");
}
else
{
Console.Write("None");
}
}
while ((Salt < 10) || Sugar < 10);

Currently you'll keep looping while either of them have been chosen 10 times. I suspect you want:
while (Salt < 10 && Sugar < 10)
Having said that, the code you've given is clearly pseudo-code anyway - it wouldn't compile for various reasons. If you could post a short but complete program demonstrating the problem, we could give an answer with more confidence. Likewise, saying "It doesn't seem to work" is akin to going to the doctor and expecting a diagnosis from "I'm not feeling well." More details please...

You declare salt and suger at the start here, but inside the loop you use Salt and Sugar. Are they properties you have defined somewhere else? Are you sure they do what you expect them to? Have you tried using the variables inside the loop instead of the properties, so your code looks like this?
int sugar = 0;
int salt = 0;
do
bottle1.choose
bottle2.choose
{
if ((bottle1 = 'Sugar') && (bottle2 = 'Sugar'))
{
Console.Write("Sugar");
sugar++;
}
else if (bottle1 = 'Salt') && bottle1 = 'Salt')
{
salt++;
Console.Write("Salt");
}
else
{
Console.Write("None");
}
}
while ((salt < 10) || sugar < 10);

Your parentheses are uneven on your if and while statements, your variable names mismatch, your bottle.choose statements must also be under the do-while loop, and you're using an assignment operator = on your conditions:
int sugar = 0;
int salt = 0;
do {
bottle1.choose();
bottle2.choose();
if ((bottle1 == 'Sugar') && (bottle2 == 'Sugar'))
{
Console.Write("Sugar");
sugar++;
}
else if ((bottle1 == 'Salt') && (bottle1 == 'Salt'))
{
salt++;
Console.Write("Salt");
}
else
{
Console.Write("None");
}
} while ((salt < 10) || (sugar < 10));

I can't tell from your question if you want to stop if EITHER salt or sugar has been chosen, or if you want to stop when 10 total items have been chosen.
If you're looking for the former, then Jon Skeet's answer will do it for you.
If you're looking for the latter, then I think you're looking for the following:
while (Salt + Sugar < 10);

If I understand the code correctly, both bottles must be of the same taste to do the increment.
First error seem to be the test condition for the "Salt", you check twice for the "bottle1", test should be :
else if (bottle1 = 'Salt') && bottle2 = 'Salt')

Your Variables names are mismatching, again you may take the condition for selection of both salt and sugar in the "while statement" itself.

Related

Looking for a more elegant DO WHILE solution

So I have some code centered around a do while loop.
string token;
var count = 0;
var checkDataLength= data.Length == 16;
do
{
count = 0;
token = GenerateToken(data, start, end);
if (checkDataLength)
{
if (Mod120Check(token))
{
count += 1;
}
}
if (IsCompliant(token))
{
count += 1;
}
}
while (count > 0);
return token;
Basically, I am generating a token and for this token to be valid, has to FAIL the Mod120Check and the IsCompliant check. I cannot change how those methods return the data.
While the above code works, I feel that its ugly and I was wondering if anyone had a better way of doing it?
Thanks
Try this:
do
{
token = GenerateToken(data, start, end);
}
while (checkDataLength && Mod120Check(token) || IsCompliant(token))
Just moving your conditions to the while.
(!) Notice that IsCompliant(token) will only be called if checkDataLength && Mod120Check(token) states false. It shouldn't cause any colateral effects, but it could, depending on what your IsCompliant method does.
You're right, it is ugly. You are using count in an unexpected way (it gets reset to zero at the top of every loop, and can go positive for two different reasons). When I see count, I expect something to start at zero and count up (or start high and count done). Try this instead:
Change var count = 0; to var goodEnough = false; up at the top
Remove the count = 0; statement
Change the two count += 1; statements to goodEnough = true;
Change the while (count > 0); to while (!goodEnough);
This emphasizes that you are starting in a "not good enough" state, and you will loop until some condition makes it good enough to continue past the loop.

Is there a "smart" way to break out of nested loops? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
(Right now I'm mostly using C#. Ideas in other languages are welcome, but please translate them to C# if you can, and be explicit.)
Something I come across time and time again is a nested loop, searching through some 2D array to find an element (typically some object), which then has to be manipulated. So of course, once you find that object, you should break out of both loops so you don't needlessly continue the search for something you already found (especially in nested loops which can traversing exponentially huge arrays).
The following code is currently my preferred way of doing it:
Obj O = null;
bool KeepLooping = true;
for (int j = 0; j < height && KeepLooping; j++)
{
for (int i = 0; i < width; i++)
{
if (ObjArray[i, j] != null && ObjArray[i, j].property == search_value)
{
O = ObjArray[i, j]; // you found it, now remember it
KeepLooping = false; // clear the flag so the outer loop will break too
break;
}
}
}
Thanks to Erik Funkenbusch, it becomes much more elegant if we do this:
Obj O = null;
for (int j = 0; j < height && O == null; j++) // much, much better idea to check O for null in the outer loop
{
for (int i = 0; i < width; i++)
{
if (ObjArray[i, j] != null && ObjArray[i, j].property == search_value)
{
O = ObjArray[i, j]; // you found it, now remember it
break;
}
}
}
No more need for that pesky extra boolean!
Nevertheless, the search for alternative or better solutions goes on. Over the years I've tried many other ways, but find them not that great for one reason or another:
Set j (the outer-loop iterator) to a value above height, which will trigger it to break automatically. Not ideal because sometimes you want to remember the i and j values where you found it.
Use foreach on the 2D array. Not ideal since foreach won't let you manipulate the collection (delete or add to it, which very typically is the reason I search for the object anyway).
Just put the 2 loops in a function that does nothing but find and return O. return effectively breaks both loops. Many times this is okay, but not always. I do this for very generic searches, but there are also quite a lot of "group searches" where I want to collectivize the traversing. In those cases, I find 2 or more objects (sometimes within the same 2D array), remember them, and only then break out of both loops.
Use a goto? (Whoa, could this be the only legit use of a goto? It's surprisingly more readable than the KeepLooping flag, especially if we have 3 or more loops.) Not ideal because coworkers will scream bloody murder. And in C#, will there be correct garbage cleanup after the goto?
Throw a custom exception? idk, i've never tried it, but it looks less readable than my currently preferred way.
Once you've found the right object, do all your object manipulation inside the inner loop, and then return; This could get messy fast. Sometimes the object manipulation involves its own loops.
There is also a very clever 7th way, thanks to User_PWY:
int size = width*height; // save this so you dont have to keep remultiplying it every iteration
for (int i = 0; i < size; i++)
{
int x = i % width; // ingenious method here
int y = i / width; // ingenious method here
O = ObjArray[x, y];
if (O != null)
break; // woohoo!
}
This effectively compacts the 2D array into one for loop for iteration. However, some criticism has pointed out that the mod and division operators are pretty slow in comparison to just i++ or j++, so it could be slower (remember we are dealing with 2D arrays of who-knows-what size). Like i commented, there should be a way to get the division and remainder in one operation because I'm pretty sure the x86 assembly code has DIV opcodes that store the quotient and remainder in separate registers, all in one DIV instruction. But how to do/use that in C#, idk.
It would be nice if C# allowed you to name loops, such as L1 and L2, and then do something like L1.break(); regardless of which loop you're inside. Alas...it cannot be done in this language. (Could there be some secret way of doing this using macros?) Is there ever gonna be a C# 6.0 with this feature implemented?
Edit: in my opinion, I judge solutions on their elegance and speed. Remember we are dealing with nested loops, which can get exponentially huge. An extra operation or comparison could make a difference.
Okay, well, tell me your preferred way, especially if it's something not listed here.
goto is a perfectly fine solution for this, Microsoft even recommends it:
The goto statement transfers the program control directly to a labeled
statement.
A common use of goto is to transfer control to a specific switch-case
label or the default label in a switch statement.
The goto statement is also useful to get out of deeply nested loops.
As for your question about object destruction, once you are out of scope for a scoped object the garbage collector should mark it for destruction, but I can't say for sure whether the behavior is the same if you use, for example, a using directive around your for loop and goto out of it as opposed to exiting scope normally.
for (int i = 0; i < width*height; i++)
{
int x=i%width
,y=i/width;
//dostuff
}
I like this way of access to 2d array.
comment 1)
There were many comments worrying that mod(%) operator could be costly, but this is integer operation we are talking about and I think that it should make no difference other solution.
comment 2)
about the macro. I couldn't find the code but managed to produce one briefly.
#define FOR2DARRAY(WIDTH,HEIGHT)
\for (int i = 0, x = 0,y = 0; i < (WIDTH)*(HEIGHT); i++, x=i%(WIDTH),y=i/(HEIGHT))
Refactoring to avoid deep nesting, possibly with cleaver usage of LINQ is probably better solution.
Goto is possible for this case (and this is essentially only case to use it) if you can't come up with better approach. Setting flag with readable name will likely cause less questions/screaming.
Do not
use exceptions for flow controls
change loop variables. Figuring out what happens is very hard in this case. I'd bet most people will accept goto as much better approach.
Not very much different, but I prefer to use the boolean flag in this way:
Obj O = null;
bool found = false;
for (int j = 0; j < height; j++)
{
for (int i = 0; i < width; i++)
{
if (ObjArray[i, j] != null && ObjArray[i, j].property = search_value)
{
O = ObjArray[i, j]; // you found it, now remember it
found = true; // clear the flag so the outer loop will break too
break;
}
}
if (found) break;
}
if (!found)
{
// The loop finished with no values found
}
else
{
// Do stuff here with the value found
}
Try this:
Obj O = ObjArray.Cast<Obj>().FirstOrDefault(obj => obj != null && obj.property == search_value);
This converts the 2D array of Obj into an IEnumerable<Obj> and gives you the first one that matches your conditions. If none of them match, Obj O is set to null.
Check it out here: https://dotnetfiddle.net/dQTJbU
Maybe I missed it in your list of options, but why can't you refactor the search into a method that returns your object?
private object FindObject(....)
{
for (int j = 0; j < height && KeepLooping; j++)
{
for (int i = 0; i < width; i++)
{
if (ObjArray[i, j] != null && ObjArray[i, j].property = search_value)
{
return ObjArray[i, j]; // you found it, now remember it
}
}
}
return null;
}
There are many many ways to do this. In your example, I would do it like this:
Obj O = null;
for (int j = 0; j < height && O == null; j++)
{
for (int i = 0; i < width; i++)
{
if (ObjArray[i, j] != null && ObjArray[i, j].property == search_value)
{
O = ObjArray[i, j]; // you found it, now remember it
break;
}
}
}
The KeepLooping variable is unnecessary in this case, and thus the simple break statement works very elegantly.
You could actually even simplify this more:
Obj O = null;
for (int j = 0; j < height && O == null; j++)
{
for (int i = 0; i < width && O == null; i++)
{
if (ObjArray[i, j] != null && ObjArray[i, j].property == search_value)
O = ObjArray[i, j]; // you found it, now remember it
}
}
Now, the break isn't even required.
Of course this may not work for all situations, but often you can utilize the result type as a state value.
FYI, the issue with modifying the collection in a foreach isn't really a problem if you do it correctly. For instance:
// Assumes ObjArray is [,] and not [][]
foreach (int item in ObjArray.ToList()) // makes a copy to iterate over
{
if (item != null && item.property == search_value) {
ObjArray[0,0] = item; // I can now modify this for no reason
break;
}
}

Is there a "label" to break nested foreach loops in C#? [duplicate]

If I have a for loop which is nested within another, how can I efficiently come out of both loops (inner and outer) in the quickest possible way?
I don't want to have to use a boolean and then have to say go to another method, but rather just to execute the first line of code after the outer loop.
What is a quick and nice way of going about this?
I was thinking that exceptions aren't cheap/should only be thrown in a truly exceptional condition etc. Hence I don't think this solution would be good from a performance perspective.
I don't feel it it is right to take advantage of the newer features in .NET (anon methods) to do something which is pretty fundamental.
Well, goto, but that is ugly, and not always possible. You can also place the loops into a method (or an anon-method) and use return to exit back to the main code.
// goto
for (int i = 0; i < 100; i++)
{
for (int j = 0; j < 100; j++)
{
goto Foo; // yeuck!
}
}
Foo:
Console.WriteLine("Hi");
vs:
// anon-method
Action work = delegate
{
for (int x = 0; x < 100; x++)
{
for (int y = 0; y < 100; y++)
{
return; // exits anon-method
}
}
};
work(); // execute anon-method
Console.WriteLine("Hi");
Note that in C# 7 we should get "local functions", which (syntax tbd etc) means it should work something like:
// local function (declared **inside** another method)
void Work()
{
for (int x = 0; x < 100; x++)
{
for (int y = 0; y < 100; y++)
{
return; // exits local function
}
}
};
Work(); // execute local function
Console.WriteLine("Hi");
C# adaptation of approach often used in C - set value of outer loop's variable outside of loop conditions (i.e. for loop using int variable INT_MAX -1 is often good choice):
for (int i = 0; i < 100; i++)
{
for (int j = 0; j < 100; j++)
{
if (exit_condition)
{
// cause the outer loop to break:
// use i = INT_MAX - 1; otherwise i++ == INT_MIN < 100 and loop will continue
i = int.MaxValue - 1;
Console.WriteLine("Hi");
// break the inner loop
break;
}
}
// if you have code in outer loop it will execute after break from inner loop
}
As note in code says break will not magically jump to next iteration of the outer loop - so if you have code outside of inner loop this approach requires more checks. Consider other solutions in such case.
This approach works with for and while loops but does not work for foreach. In case of foreach you won't have code access to the hidden enumerator so you can't change it (and even if you could IEnumerator doesn't have some "MoveToEnd" method).
Acknowledgments to inlined comments' authors:
i = INT_MAX - 1 suggestion by Meta
for/foreach comment by ygoe.
Proper IntMax by jmbpiano
remark about code after inner loop by blizpasta
This solution does not apply to C#
For people who found this question via other languages, Javascript, Java, and D allows labeled breaks and continues:
outer: while(fn1())
{
while(fn2())
{
if(fn3()) continue outer;
if(fn4()) break outer;
}
}
Use a suitable guard in the outer loop. Set the guard in the inner loop before you break.
bool exitedInner = false;
for (int i = 0; i < N && !exitedInner; ++i) {
.... some outer loop stuff
for (int j = 0; j < M; ++j) {
if (sometest) {
exitedInner = true;
break;
}
}
if (!exitedInner) {
... more outer loop stuff
}
}
Or better yet, abstract the inner loop into a method and exit the outer loop when it returns false.
for (int i = 0; i < N; ++i) {
.... some outer loop stuff
if (!doInner(i, N, M)) {
break;
}
... more outer loop stuff
}
Don't quote me on this, but you could use goto as suggested in the MSDN. There are other solutions, as including a flag that is checked in each iteration of both loops. Finally you could use an exception as a really heavyweight solution to your problem.
GOTO:
for ( int i = 0; i < 10; ++i ) {
for ( int j = 0; j < 10; ++j ) {
// code
if ( break_condition ) goto End;
// more code
}
}
End: ;
Condition:
bool exit = false;
for ( int i = 0; i < 10 && !exit; ++i ) {
for ( int j = 0; j < 10 && !exit; ++j ) {
// code
if ( break_condition ) {
exit = true;
break; // or continue
}
// more code
}
}
Exception:
try {
for ( int i = 0; i < 10 && !exit; ++i ) {
for ( int j = 0; j < 10 && !exit; ++j ) {
// code
if ( break_condition ) {
throw new Exception()
}
// more code
}
}
catch ( Exception e ) {}
Is it possible to refactor the nested for loop into a private method? That way you could simply 'return' out of the method to exit the loop.
It seems to me like people dislike a goto statement a lot, so I felt the need to straighten this out a bit.
I believe the 'emotions' people have about goto eventually boil down to understanding of code and (misconceptions) about possible performance implications. Before answering the question, I will therefore first go into some of the details on how it's compiled.
As we all know, C# is compiled to IL, which is then compiled to assembler using an SSA compiler. I'll give a bit of insights into how this all works, and then try to answer the question itself.
From C# to IL
First we need a piece of C# code. Let's start simple:
foreach (var item in array)
{
// ...
break;
// ...
}
I'll do this step by step to give you a good idea of what happens under the hood.
First translation: from foreach to the equivalent for loop (Note: I'm using an array here, because I don't want to get into details of IDisposable -- in which case I'd also have to use an IEnumerable):
for (int i=0; i<array.Length; ++i)
{
var item = array[i];
// ...
break;
// ...
}
Second translation: the for and break is translated into an easier equivalent:
int i=0;
while (i < array.Length)
{
var item = array[i];
// ...
break;
// ...
++i;
}
And third translation (this is the equivalent of the IL code): we change break and while into a branch:
int i=0; // for initialization
startLoop:
if (i >= array.Length) // for condition
{
goto exitLoop;
}
var item = array[i];
// ...
goto exitLoop; // break
// ...
++i; // for post-expression
goto startLoop;
While the compiler does these things in a single step, it gives you insight into the process. The IL code that evolves from the C# program is the literal translation of the last C# code. You can see for yourself here: https://dotnetfiddle.net/QaiLRz (click 'view IL')
Now, one thing you have observed here is that during the process, the code becomes more complex. The easiest way to observe this is by the fact that we needed more and more code to ackomplish the same thing. You might also argue that foreach, for, while and break are actually short-hands for goto, which is partly true.
From IL to Assembler
The .NET JIT compiler is an SSA compiler. I won't go into all the details of SSA form here and how to create an optimizing compiler, it's just too much, but can give a basic understanding about what will happen. For a deeper understanding, it's best to start reading up on optimizing compilers (I do like this book for a brief introduction: http://ssabook.gforge.inria.fr/latest/book.pdf ) and LLVM (llvm.org).
Every optimizing compiler relies on the fact that code is easy and follows predictable patterns. In the case of FOR loops, we use graph theory to analyze branches, and then optimize things like cycli in our branches (e.g. branches backwards).
However, we now have forward branches to implement our loops. As you might have guessed, this is actually one of the first steps the JIT is going to fix, like this:
int i=0; // for initialization
if (i >= array.Length) // for condition
{
goto endOfLoop;
}
startLoop:
var item = array[i];
// ...
goto endOfLoop; // break
// ...
++i; // for post-expression
if (i >= array.Length) // for condition
{
goto startLoop;
}
endOfLoop:
// ...
As you can see, we now have a backward branch, which is our little loop. The only thing that's still nasty here is the branch that we ended up with due to our break statement. In some cases, we can move this in the same way, but in others it's there to stay.
So why does the compiler do this? Well, if we can unroll the loop, we might be able to vectorize it. We might even be able to proof that there's just constants being added, which means our whole loop could vanish into thin air. To summarize: by making the patterns predictable (by making the branches predictable), we can proof that certain conditions hold in our loop, which means we can do magic during the JIT optimization.
However, branches tend to break those nice predictable patterns, which is something optimizers therefore kind-a dislike. Break, continue, goto - they all intend to break these predictable patterns- and are therefore not really 'nice'.
You should also realize at this point that a simple foreach is more predictable then a bunch of goto statements that go all over the place. In terms of (1) readability and (2) from an optimizer perspective, it's both the better solution.
Another thing worth mentioning is that it's very relevant for optimizing compilers to assign registers to variables (a process called register allocation). As you might know, there's only a finite number of registers in your CPU and they are by far the fastest pieces of memory in your hardware. Variables used in code that's in the inner-most loop, are more likely to get a register assigned, while variables outside of your loop are less important (because this code is probably hit less).
Help, too much complexity... what should I do?
The bottom line is that you should always use the language constructs you have at your disposal, which will usually (implictly) build predictable patterns for your compiler. Try to avoid strange branches if possible (specifically: break, continue, goto or a return in the middle of nothing).
The good news here is that these predictable patterns are both easy to read (for humans) and easy to spot (for compilers).
One of those patterns is called SESE, which stands for Single Entry Single Exit.
And now we get to the real question.
Imagine that you have something like this:
// a is a variable.
for (int i=0; i<100; ++i)
{
for (int j=0; j<100; ++j)
{
// ...
if (i*j > a)
{
// break everything
}
}
}
The easiest way to make this a predictable pattern is to simply eliminate the if completely:
int i, j;
for (i=0; i<100 && i*j <= a; ++i)
{
for (j=0; j<100 && i*j <= a; ++j)
{
// ...
}
}
In other cases you can also split the method into 2 methods:
// Outer loop in method 1:
for (i=0; i<100 && processInner(i); ++i)
{
}
private bool processInner(int i)
{
int j;
for (j=0; j<100 && i*j <= a; ++j)
{
// ...
}
return i*j<=a;
}
Temporary variables? Good, bad or ugly?
You might even decide to return a boolean from within the loop (but I personally prefer the SESE form because that's how the compiler will see it and I think it's cleaner to read).
Some people think it's cleaner to use a temporary variable, and propose a solution like this:
bool more = true;
for (int i=0; i<100; ++i)
{
for (int j=0; j<100; ++j)
{
// ...
if (i*j > a) { more = false; break; } // yuck.
// ...
}
if (!more) { break; } // yuck.
// ...
}
// ...
I personally am opposed to this approach. Look again on how the code is compiled. Now think about what this will do with these nice, predictable patterns. Get the picture?
Right, let me spell it out. What will happen is that:
The compiler will write out everything as branches.
As an optimization step, the compiler will do data flow analysis in an attempt to remove the strange more variable that only happens to be used in control flow.
If succesful, the variable more will be eliminated from the program, and only branches remain. These branches will be optimized, so you will get only a single branch out of the inner loop.
If unsuccesful, the variable more is definitely used in the inner-most loop, so if the compiler won't optimize it away, it has a high chance to be allocated to a register (which eats up valuable register memory).
So, to summarize: the optimizer in your compiler will go into a hell of a lot of trouble to figure out that more is only used for the control flow, and in the best case scenario will translate it to a single branch outside of the outer for loop.
In other words, the best case scenario is that it will end up with the equivalent of this:
for (int i=0; i<100; ++i)
{
for (int j=0; j<100; ++j)
{
// ...
if (i*j > a) { goto exitLoop; } // perhaps add a comment
// ...
}
// ...
}
exitLoop:
// ...
My personal opinion on this is quite simple: if this is what we intended all along, let's make the world easier for both the compiler and readability, and write that right away.
tl;dr:
Bottom line:
Use a simple condition in your for loop if possible. Stick to the high-level language constructs you have at your disposal as much as possible.
If everything fails and you're left with either goto or bool more, prefer the former.
You asked for a combination of quick, nice, no use of a boolean, no use of goto, and C#. You've ruled out all possible ways of doing what you want.
The most quick and least ugly way is to use a goto.
factor into a function/method and use early return, or rearrange your loops into a while-clause. goto/exceptions/whatever are certainly not appropriate here.
def do_until_equal():
foreach a:
foreach b:
if a==b: return
The cleanest, shortest, and most reusable way is a self invoked anonymous function:
no goto
no label
no temporary variable
no named function
One line shorter than the top answer with anonymous method.
new Action(() =>
{
for (int x = 0; x < 100; x++)
{
for (int y = 0; y < 100; y++)
{
return; // exits self invoked lambda expression
}
}
})();
Console.WriteLine("Hi");
Sometimes nice to abstract the code into it's own function and than use an early return - early returns are evil though : )
public void GetIndexOf(Transform transform, out int outX, out int outY)
{
outX = -1;
outY = -1;
for (int x = 0; x < Columns.Length; x++)
{
var column = Columns[x];
for (int y = 0; y < column.Transforms.Length; y++)
{
if(column.Transforms[y] == transform)
{
outX = x;
outY = y;
return;
}
}
}
}
Since I first saw break in C a couple of decades back, this problem has vexed me. I was hoping some language enhancement would have an extension to break which would work thus:
break; // our trusty friend, breaks out of current looping construct.
break 2; // breaks out of the current and it's parent looping construct.
break 3; // breaks out of 3 looping constructs.
break all; // totally decimates any looping constructs in force.
I've seen a lot of examples that use "break" but none that use "continue".
It still would require a flag of some sort in the inner loop:
while( some_condition )
{
// outer loop stuff
...
bool get_out = false;
for(...)
{
// inner loop stuff
...
get_out = true;
break;
}
if( get_out )
{
some_condition=false;
continue;
}
// more out loop stuff
...
}
The easiest way to end a double loop would be directly ending the first loop
string TestStr = "The frog jumped over the hill";
char[] KillChar = {'w', 'l'};
for(int i = 0; i < TestStr.Length; i++)
{
for(int E = 0; E < KillChar.Length; E++)
{
if(KillChar[E] == TestStr[i])
{
i = TestStr.Length; //Ends First Loop
break; //Ends Second Loop
}
}
}
Loops can be broken using custom conditions in the loop, allowing as to have clean code.
static void Main(string[] args)
{
bool isBreak = false;
for (int i = 0; ConditionLoop(isBreak, i, 500); i++)
{
Console.WriteLine($"External loop iteration {i}");
for (int j = 0; ConditionLoop(isBreak, j, 500); j++)
{
Console.WriteLine($"Inner loop iteration {j}");
// This code is only to produce the break.
if (j > 3)
{
isBreak = true;
}
}
Console.WriteLine("The code after the inner loop will be executed when breaks");
}
Console.ReadKey();
}
private static bool ConditionLoop(bool isBreak, int i, int maxIterations) => i < maxIterations && !isBreak;
With this code we ontain the following output:
External loop iteration 0
Inner loop iteration 0
Inner loop iteration 1
Inner loop iteration 2
Inner loop iteration 3
Inner loop iteration 4
The code after the inner loop will be executed when breaks
I remember from my student days that it was said it's mathematically provable that you can do anything in code without a goto (i.e. there is no situation where goto is the only answer). So, I never use goto's (just my personal preference, not suggesting that i'm right or wrong)
Anyways, to break out of nested loops I do something like this:
var isDone = false;
for (var x in collectionX) {
for (var y in collectionY) {
for (var z in collectionZ) {
if (conditionMet) {
// some code
isDone = true;
}
if (isDone)
break;
}
if (isDone)
break;
}
if (isDone)
break;
}
... i hope that helps for those who like me are anti-goto "fanboys" :)
That's how I did it. Still a workaround.
foreach (var substring in substrings) {
//To be used to break from 1st loop.
int breaker=1;
foreach (char c in substring) {
if (char.IsLetter(c)) {
Console.WriteLine(line.IndexOf(c));
\\setting condition to break from 1st loop.
breaker=9;
break;
}
}
if (breaker==9) {
break;
}
}
Another option which is not mentioned here which is both clean and does not rely on newer .NET features is to consolidate the double loop into a single loop over the product. Then inside the loop the values of the counters can be calculated using simple math:
int n; //set to max of first loop
int m; //set to max of second loop
for (int k = 0; k < n * m; k++)
{
//calculate the values of i and j as if there was a double loop
int i = k / m;
int j = k % m;
if(exitCondition)
{
break;
}
}
People often forget that the 2nd statement of the for loops themselves are the break conditions, so there is no need to have additional ifs within the code.
Something like this works:
bool run = true;
int finalx = 0;
int finaly = 0;
for (int x = 0; x < 100 && run; x++)
{
finalx = x;
for (int y = 0; y < 100 && run; y++)
{
finaly = y;
if (x == 10 && y == 50) { run = false; }
}
}
Console.WriteLine("x: " + finalx + " y: " + finaly); // outputs 'x: 10 y: 50'
just use return inside the inner loop and the two loops will be exited...
I would just set a flag.
var breakOuterLoop = false;
for (int i = 0; i < 30; i++)
{
for (int j = 0; j < 30; j++)
{
if (condition)
{
breakOuterLoop = true;
break;
}
}
if (breakOuterLoop){
break;
}
}
Throw a custom exception which goes out outter loop.
It works for for,foreach or while or any kind of loop and any language that uses try catch exception block
try
{
foreach (object o in list)
{
foreach (object another in otherList)
{
// ... some stuff here
if (condition)
{
throw new CustomExcpetion();
}
}
}
}
catch (CustomException)
{
// log
}
bool breakInnerLoop=false
for(int i=0;i<=10;i++)
{
for(int J=0;i<=10;i++)
{
if(i<=j)
{
breakInnerLoop=true;
break;
}
}
if(breakInnerLoop)
{
continue
}
}
As i see you accepted the answer in which the person refers you goto statement, where in modern programming and in expert opinion goto is a killer, we called it a killer in programming which have some certain reasons, which i will not discuss it over here at this point, but the solution of your question is very simple, you can use a Boolean flag in this kind of scenario like i will demonstrate it in my example:
for (; j < 10; j++)
{
//solution
bool breakme = false;
for (int k = 1; k < 10; k++)
{
//place the condition where you want to stop it
if ()
{
breakme = true;
break;
}
}
if(breakme)
break;
}
simple and plain. :)
Did you even look at the break keyword? O.o
This is just pseudo-code, but you should be able to see what I mean:
<?php
for(...) {
while(...) {
foreach(...) {
break 3;
}
}
}
If you think about break being a function like break(), then it's parameter would be the number of loops to break out of. As we are in the third loop in the code here, we can break out of all three.
Manual: http://php.net/break
I think unless you want to do the "boolean thing" the only solution is actually to throw. Which you obviously shouldn't do..!

Enumerable.Range(...).Any(...) outperforms a basic loop: Why?

I was adapting a simple prime-number generation one-liner from Scala to C# (mentioned in a comment on this blog by its author). I came up with the following:
int NextPrime(int from)
{
while(true)
{
n++;
if (!Enumerable.Range(2, (int)Math.Sqrt(n) - 1).Any((i) => n % i == 0))
return n;
}
}
It works, returning the same results I'd get from running the code referenced in the blog. In fact, it works fairly quickly. In LinqPad, it generated the 100,000th prime in about 1 second. Out of curiosity, I rewrote it without Enumerable.Range() and Any():
int NextPrimeB(int from)
{
while(true)
{
n++;
bool hasFactor = false;
for (int i = 2; i <= (int)Math.Sqrt(n); i++)
{
if (n % i == 0) hasFactor = true;
}
if (!hasFactor) return n;
}
}
Intuitively, I'd expect them to either run at the same speed, or even for the latter to run a little faster. In actuality, computing the same value (100,000th prime) with the second method, takes 12 seconds - It's a staggering difference.
So what's going on here? There must be fundamentally something extra happening in the second approach that's eating up CPU cycles, or some optimization going on the background of the Linq examples. Anybody know why?
For every iteration of the for loop, you are finding the square root of n. Cache it instead.
int root = (int)Math.Sqrt(n);
for (int i = 2; i <= root; i++)
And as other have mentioned, break the for loop as soon as you find a factor.
The LINQ version short circuits, your loop does not. By this I mean that when you have determined that a particular integer is in fact a factor the LINQ code stops, returns it, and then moves on. Your code keeps looping until it's done.
If you change the for to include that short circuit, you should see similar performance:
int NextPrimeB(int from)
{
while(true)
{
n++;
for (int i = 2; i <= (int)Math.Sqrt(n); i++)
{
if (n % i == 0) return n;;
}
}
}
It looks like this is the culprit:
for (int i = 2; i <= (int)Math.Sqrt(n); i++)
{
if (n % i == 0) hasFactor = true;
}
You should exit the loop once you find a factor:
if (n % i == 0){
hasFactor = true;
break;
}
And as other have pointed out, move the Math.Sqrt call outside the loop to avoid calling it each cycle.
Enumerable.Any takes an early out if the condition is successful while your loop does not.
The enumeration of source is stopped as soon as the result can be determined.
This is an example of a bad benchmark. Try modifying your loop and see the difference:
if (n % i == 0) { hasFactor = true; break; }
}
throw new InvalidOperationException("Cannot satisfy criteria.");
In the name of optimization, you can be a little more clever about this by avoiding even numbers after 2:
if (n % 2 != 0)
{
int quux = (int)Math.Sqrt(n);
for (int i = 3; i <= quux; i += 2)
{
if (n % i == 0) return n;
}
}
There are some other ways to optimize prime searches, but this is one of the easier to do and has a large payoff.
Edit: you may want to consider using (int)Math.Sqrt(n) + 1. FP functions + round-down could potentially cause you to miss a square of a large prime number.
At least part of the problem is the number of times Math.Sqrt is executed. In the LINQ query this is executed once but in the loop example it's executed N times. Try pulling that out into a local and reprofiling the application. That will give you a more representative break down
int limit = (int)Math.Sqrt(n);
for (int i = 2; i <= limit; i++)

Messagebox If Loop

I have a simple message box pop up when a variable is achieved. It spirals into infinity since I have no stopper. Perhaps it's just my inability to figure out where the stopper is to be placed, but it doesn't seem to halt no matter my solution.
if (number == 10)
{
MessageBox.Show("Woot!");
}
Without more code, you can either use a break (as it sounds like you are using a loop), or set your number to something other than 10
while(switchstatement)
{
...logic...
if(number == 10)
{
MessageBox.Show("woot");
break;
}
...more logic...
}
Or, you can set the switch that kills your loop
while(switchstatement)
{
...logic...
if(number == 10)
{
MessageBox.Show("woot");
switchstatement = false;
}
...more logic...
}
That is based off of limited code...so you may have to provide more code if this is not correct.
You are using a variable but i don't see where you set the value so i assume that you never change it in the loop. Hence you are in an infinite loop.
You could use a for-loop instead
for(int number = 0; number < 10; number++)
{
MessageBox.Show("Woot!");
}
or in a while
int number = 0;
while(number++ < 10)
{
MessageBox.Show("Woot!");
}
C# Increment Int
++ Operator (C# Reference)

Categories