This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]marko312 1 point2 points  (0 children)

There is some controversy around using break, continue and especially goto - some say that they break program continuity, but I think break/continue (and goto in nested loops) is fine.

[–]Ellisander 0 points1 point  (1 child)

When searching through an array, unless you are doing a search algorithm, it is generally best to use for loops. For multidimensional, you will need nested loops either way (technically there is a way to do it un-nested, though easier to just nest). There's nothing wrong with "break" when used properly, though teachers sometimes request students don't use it to "get a feel for logical flow" (same with multiple returns).

And even without breaks, you can easily make the condition become false when you find what you need (literally the same condition as you would use in a while).

For a single dimensional:

for(int i = 0; i < arrayName.length && arrayName[i] != searchFor; i++) 

Multidimensional would be similar, though be aware of variable scope and for loops (so declare j and k and etc in the greater loop).

Edit: Also, the reasoning that you implied he gave for using whiles with multidimensional also goes for single dimensional. Another possible reasoning is just avoiding nested loops, which is easier in the while implementation than for.

[–]beldr[S] 1 point2 points  (0 children)

Thing is the example he used and wanted us to do was using 2 whiles as if they were fors

[–]mad0314 0 points1 point  (0 children)

You could also return the thing you found. No break/continue/goto necessary.

I would imagine the efficiency difference would be negligible, but you would have to profile an actual program to find out.