for loop skipping a line - c#

I'm super new to c# and programming in general. I'm trying to do some exercises online to familiarize myself with the basics of the language before I start school next month.
I've written a super simple program and I just can't understand why it's doing what it's doing and I haven't been able to find an answer anywhere. Here's the code.
int i, j, rows;
Console.Write("\n\n");
Console.Write("Display the pattern like right angle triangle which repeat a number in a row:\n");
Console.Write("-------------------------------------------------------------------------------");
Console.Write("\n\n");
Console.Write("Input number of rows : ");
rows = Convert.ToInt32(Console.ReadLine());
for (i = 1; i <= rows; i++)
{
for (j = 1; j <= i; j++)
Console.Write("{0}", i);
Console.Write("\n");
}
All this program is suppose to do is a simple pyramid with the same number.
My question is that in the second for loop it writes i but then it re-evaluates j++ and j<= instead of writing \n until the end of the last run of the loop. I don't understand why? The program works but I am not understanding why. Isn't the for loop always suppose to execute everything in it unless you break it?
thanks and sorry for the very novice question but its driving me nuts!

In programming every statement have a scope block in which it run.
By default for loop have only one statement scope that just comes after it. If we wanted to run more then one statement in for loop scope then we use curly braces {} to define the code block.
in your case you need to use curly braces like this to run both statements.
for (j = 1; j <= i; j++)
{
Console.Write("{0}", i);
Console.Write("\n");
}
its best programming practices to used braces {} in all you conditional and looping constructs. It make easy to read and understand the code.

A for loop will execute everything in its scope. Without using { } the scope of a for loop is the next line after it. To execute more than one command you need to put them in curly braces like so:
for (j = 1; j <= i; j++)
{
Console.Write("{0}", i);
Console.Write("\n");
}
It's generally best practice to always have the { } for readability and to easily update the loop if needed. Though you could write your for loop like so and it would be perfectly readable.
for (i = 1; i <= rows; i++)
for (j = 1; j <= i; j++)
{
Console.Write("{0}", i);
Console.Write("\n");
}
The above code will do the same thing keeping the second for loop in the scope of the first.
As an aside, I noticed you declared your variables outside of the for loop, being new to programming you may not be aware of certain features of the for loop.
You can declare your iterator right in the for loop:
for (int i = 1; i <= rows; ++i)
In most cases it's better to declare your iterator in the for loop like this as it gives 'i' the same scope as the for loop.
Another neat feature of the for loop is that all the options between the semi-colons are actually optional. So for instance, if you declared your iterator outside the for loop you can omit it in the for loop:
int i = 1;
for (; i<= rows; ++i)
You can omit any part or all of it even:
for (;;) // a perfectly valid for loop that will loop forever.
You can even have multiple iterators:
for (int i = 0, j = 0; i < 5; ++i, ++j)

Your expectation that in every iteration of inner for loop both Console.Write statements will get executed is wrong:
for (j = 1; j <= i; j++)
Console.Write("{0}", i); //inner for loop scope starts and ends on this statement
There is no curly brace after inner for loop. So, by default ONLY first statement encountered after for statement will be treated under the scope of inner for loop.
Outer for loop has a curly brace as shown below:
for (i = 1; i <= rows; i++)
{//outer for loop scope starts here
for (j = 1; j <= i; j++)
Console.Write("{0}", i);
Console.Write("\n");
}//outer for loop scope ends here
So in every iteration of outer for loop the whole inner for loop and the Console.Write("\n"); will execute.
As a general practice, if you have only one statement to execute inside your for loop then you indent it with a tab as depicted in your code snippet as well.

Related

Is it possible to pass a variable into a for loop?

Is it possible to initialize 'int number' and pass it a value from the user input? I'm wondering if there's a cleaner way to do this by initializing number outside of the for loop.
for (int number = Convert.ToInt16(Console.ReadLine()); number < 10; number++)
{
Console.WriteLine(number);
}
I would like to do something like this, where a variables is initialed outside the loop, then handed directly in. - However this doesn't seem to work.
int n;
for (n; n<10; n++)
{
Console.Writeline(n)
}
I understand that it can be assigned and passed into the loop, but is it possible to do this without having to?
int n = Convert.ToInt16(Console.ReadLine());
for (int i = n; i<10; i++)
Console.Writeline(i);
in other words, can I use int n, without having to change it to i?
It's very close to what you had, just leave off the first part.
int n = 0;
for (; n < 10; n++)
{
Console.WriteLine(n)
}
Yeah this works, just tried in jsfiddle (https://dotnetfiddle.net/ZkL4BP). Just make sure nis initialized to something prior to the loop just int n gives a variable not initialized error.
As others are pointing out it is definitely an odd pattern, typically you want your for loop counter to only live the duration of the loop, and do whatever manipulation to other variables within the block. But it is accepted by the compiler.
You can do that by simply omitting the first part of the for statement
int n = Convert.ToInt16(Console.ReadLine());
for (; n<10; n++)
Console.Writeline(n);
Parts of the for statement are statements themselves and may contain arbitrary stuff - including an empty statement.
That said, you need to keep in mind that your variable is changed inside the loop. It's not great from the aspect of readability, so I wouldn't recommend it.

Loop stops all code after one iteration

I have a loop which in theory should loop 40000 times but exits and doesn't continue with code after the loop, just after one iteration. I figured that I wasnt being a silly willy about the for-loops since it didn't continue after the loops at all, so that might be something with restrictions for Lists? Or mayby something about the VS-debugger that isn't working preperly? (probably not tho...)
Edit: Thanks for pointing out that the last layer was pointless. I edited the code, but the problem persists.
Edit2: To clarify, the code does not result in an exception, or breaks. It just stops without any notifications, and shows the form(since I do a windows forms application). Just... it just don't want to continue and skips the rest of the code.
for (int i = 0; i < hiddenLayerDepth - 1; i++)
{
Connectors.Add(new List<List<List<List<Connector>>>>());
for (int j = 0; j < playfieldSize; j++)
{
Connectors[i].Add(new List<List<List<Connector>>>());
for (int k = 0; k < playfieldSize; k++)
{
Connectors[i][j].Add(new List<List<Connector>>());
for (int l = 0; l < playfieldSize; l++)
{
Connectors[i][j][k][l].Add(new Connector());
}
}
}
}
hiddenLayerDepth is set to 5 when entering the loop, and playfieldSize is set to 10. It enters the innermost loop and executes the code inside, then it just stops without increasing m.
Missing
Connectors[i][j][k].Add(new List<List<Connector>>());
If you know the sizes you should just create and array up front
Well, I tried to add a 'Connector' where there were no list. The List that contained the lists that would countain the Connectors was not added.

Big O Analysis for Algorithm

Next in my series of Big O questions that I can't find the answer to
Take the following example
for(int i = 0; i < someNumber; i++)
{
for(int j = i; j < someNumber; j++)
{
DoSomething();
}
}
Would this still be considered O(n^2)? I only ask because I feel that this has to be less that O(n^2), since the inner loop is executing less and less for every iteration of i (since j is starting closer and closer to someNumber).
Thanks
The outer loop runs n times. The inner loop starts out running n times, but decreases with each iteration of the outer loop, until the last iteration where it only runs once. The code inside the inner loop will run
n + (n−1) + ... + 2 + 1
times.
That can be simplified to n(n + 1)/2 (proof), or n2/2 + n/2, or finally (n2 + n) / 2. Since the first term is n2, the algorithm is in O(n2).

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..!

Bidirectional Bubble sort c#

I have a homework assignment of coding a bidirectional bubble sort. Can someone please see if my logic is correct with respect to it. I Don't want code as I want to figure it out myself. I just want a logic check of how i understand it.
As i understand the Bidirectional Bubble sort you implement 2 for loops one starting at position 1 in the list and performing a normal bubble sort. As the first for loop reaches the end a second one is implemented working in reverse. I just don't completely understand what the terminating conditions for each loop would be.
Would the for loop conditions be something as follows?
loop 1 - for(i = 0; i < Count -i; i++)
loop 2 - for(j = Count - i; j > i; j--)
in each loop the swap conditions would be specified.
Thanks
The "classic" bubble sort goes through the entire array on each iteration, so the loops should be
for(i = 0; i < Count - 1; i++)
and
for(j = Count - 1; j > 0; j--)
Both loops skip one index: the first loop skips the last index, while the second loop skips the initial one. This is so that your code could safely compare data[i] to data[i+1], and data[j] to data[j-1].
EDIT The "optimized" bubble sort skips the initial k elements on k-th iteration. Since your bubble sort is bidirectional, you will be able to skip the initial k and the tail k elements, like this:
int k = 0;
do { // The outer loop
...
for(int i = k; i < Count - k - 1; i++)
...
for(int j = Count - k - 1; j > k ; j--)
...
k++;
} while (<there were swaps>);
bidirectional bubble sort works like this:
instead of passing the list from bottom to top every time (bubble sort) you start one time at the bottom and every second time from the top of the list.
the wikipedia article does a way better job at explaining it:
http://en.wikipedia.org/wiki/Cocktail_sort
- rich

Categories