I am trying to get my loop to stop when i is equal to the loopEnd variable. Here is the code:
for (int i = loopStart; i < loopEnd; i++)
At the moment it stops when i is greater than loopEnd, but the program won't run if I replace < with =, and it won't work if I use ==.
No, currently it will stop when i is equal to loopEnd (because then i is not less than loopEnd). If you want it only stop when i is greater than loopEnd, use <= instead:
for (int i = loopStart; i <= loopEnd; i++)
Note that this approach has problems if loopEnd is int.MaxValue - you'll loop forever, because when i is incremented, it will become int.MinValue which is again less than loopEnd (unless you're in a checked context, in which case an exception will be thrown).
This may well not be an issue for you, but it's worth being aware of.
for (int i = loopStart; i <= loopEnd; i++)
//^ apply less or equal operator
for (int i = loopStart; i <= loopEnd; i++)
Is that what you want?
Use <= with loopEnd in your loop. Like;
for (int i = loopStart; i <= loopEnd; i++)
Use i != loopEnd. This condition indicates when to enter the loop, rather than when to stop entering.
As Chris mentions in his comment, it's mostly better to use <=, as you might increment i within the body and skip loopEnd.
Related
Why doesnt this for loop work while the while loop does
for (int i = 0; i > 10; i++)
{
Console.WriteLine(i);
}
int j = 1;
while(j != 11)
{
Console.WriteLine(j);
j++;
}
It's easy to mix up comparers. A good way to remember for me is the heart. <3 because I know that's read as "Less than three".
It's easy to get confused when starting out, you just mixed up the condition.
As of why your for does not work is because it starts with i = 0 then checks if if 0 is greater than 10 which is not that's why it will not excute the loop body and terminates the loop.
In your while loop, initially j = 1 then while checks if 1 is not equal to 11, which is true so loop body will execute until j is not equal to 11.
I'm using C# to compare data in different sheets in excel, and need to write the pass/fail result into the excel as well.
But for this part code, I only get the result of 'fail' in the excel, even the result should be 'pass'.
Anyone could have a look please?
for (i = 1; i <= baseline.GetLength(0); i++)
for (j = 1; j <= baseline.GetLength(1); j++)
{
if (baseline[i, j]?.ToString() == result_PriceUpdate[i, j]?.ToString()) goto EndofLoop1;
if (baseline[i, j]?.ToString() != result_PriceUpdate[i, j]?.ToString()) goto EndofLoop2;
}
EndofLoop1:
result_file.WriteResultToExcel("Result Summary", 2, 2, "pass");
EndofLoop2:
result_file.WriteResultToExcel("Result Summary", 2, 2, "fail");
There's no way the code in the question will ever look at more than the first cell.
The only difference between the two if() conditions is one uses == while the other uses !=; one of those conditions will always be true. Thus the very first cell will always break out of the loop. It's the same as if you had written this code, with no loop at all:
if (baseline[1, 1]?.ToString() == result_PriceUpdate[1, 1]?.ToString())
goto EndofLoop1;
if (baseline[1, 1]?.ToString() != result_PriceUpdate[1, 1]?.ToString())
goto EndofLoop2;
EndofLoop1:
result_file.WriteResultToExcel("Result Summary", 2, 2, "pass");
EndofLoop2:
result_file.WriteResultToExcel("Result Summary", 2, 2, "fail");
Maybe you're relying on the ?. null conditional operator to create comparisons with null, with the idea this will behave the same as it does in SQL, where comparing a value with null could produce false for both the != and == conditions. That won't happen here.
Worse, the jump to EndOfLoop1 doesn't end the code. The EndOfLoop2 section is still part of the method, and it will also run. Once the second section runs, it replaces the work from the first section. Even when you pass, the result you'll see in the file is still "fail".
More than that, if somehow no condition in the loop is ever true, both named sections would still run after the loop finished.
Better practice here is simply don't use goto. There's no need, and it clearly confused things. Instead, set a string variable to either "pass" or "fail" and change i and j to int.MaxValue so the loop exits right away naturally. Then only have one WriteResultToExcel() to write out the string variable.
The obvious mistake with the loop means the code in the question is unfortunately not clear enough to determine your real intent. I will suggest a solution based on the idea you want to pass only if all cells pass, and if any cells fails that will fail the entire data set:
string result = "pass";
for (i = 0; i < baseline.GetLength(0); i++)
for (j = 0; j < baseline.GetLength(1); j++)
{
if (baseline[i, j]?.ToString() != result_PriceUpdate[i, j]?.ToString())
{
result = "fail";
i = int.MaxValue;
j = int.MaxValue;
}
}
result_file.WriteResultToExcel("Result Summary", 2, 2, result);
I also have a question about starting with 1, rather than 0. C# arrays start at 0, but you never try to check the 0 positions for either dimension of the arrays, and this seems like a clear mistake.
Finally I got the issue fixed. The loop was incorrect:
for (i = 1; i <= baseline.GetLength(0); i++)
for (j = 1; j <= baseline.GetLength(1); j++)
It should be :
for (i = 1; i < baseline.GetLength(0); ++i)
for (j = 1; j < baseline.GetLength(1); ++j)
A standard "for" loop I use is something like that:
for (int i = 0; i < x; i++)
which increments i by 1 every time after it passes thru a loop.
I was wondering if there is anything like a VB's Step n operation in C#'s "for" loop. I googled and found out the only thing I can possibly do is (assume n=2)
for (int i = 0; i < x; i += 2)
That's fair enough. But that brings me to the next question. What if I want to change a loop that increments i BEFORE it goes into it, like:
for (int i = 0; i < x; ++i)
Is there any elegant way to do it, or do I need to go into first loop already with i incremented and increment it at the end of each loop OR before beginning all loops after the first one OR do other crazy stuff?
i += 2
for (int i = 0; i < x; i++)
{ i++; }
or
i += 2
for (int i = 0; i < x; i += 2)
or
for (int i = 0 - 2; i < x - 2; i += 2)
I assume incrementing before a loop might not be possible in all cases, hence i thought there should be some other way to do it.
I was wondering if there is anything like a VB's Step n
You have the right C# equivalent:
for (int i = 0; i < x; i += 2)
What if I want to change a loop that increments i BEFORE it goes into it
I may be missing something, but it sounds like you just want to change your starting value:
for (int i = 1; i < x; i++)
Also note that:
using ++i or i++ makes no real difference here, since you're not doing anything with the return value within the for statement, which is the only difference between using ++i and i++
you can't do the following:
i += 2;
for (int i = 0; i < x; i += 2)
because you can't re-declare i as part of the for loop if it;'s already declared outside of the loop.
EDIT
The for loop for (initializer; condition; iterator) is functionally equivalent to:
{
initializer;
while(condition)
{
.. do something
iterator;
}
}
It sounds like you want some sort of for loop that is equivalent to:
{
initializer;
while(condition)
{
iterator;
.. do something
}
}
there is no such single-statement construct in C#. If you want that series of events you'll have to use a while loop like the above or change the statements in your for loop to provide equivalent functionality.
Just initialize i to 2 to start at 2 rather than trying to execute the looping statement before the body.
I have this code
for (short i = 100; i >= 1; i--)
{OutputFormattedXmlElement("test", i.ToString());}
i am using the "test" to populate a dropdownlist
<select id="list><xsl:apply-templates select="/sales/test">...
My problem is that in the dropdownlist it shows the 1 as the default (correct) but it is at the bottom of the list and i want it at the top.
Where do i have to make a change? Is there any other way except javascript?
Thanks in advance!
You're looping from 100 down to 1, meaning that 100 is the first item and 1 is the last. It would seem to me that reversing the loop might give you better results.
Can you just reverse your for loop?
for (short i = 1; i <= 100; i++)
{OutputFormattedXmlElement("test", i.ToString());}
For your situation, is it valid to simply flip the for loop?
for (short i = 1; i <= 100; i++)
...
Using C# (or VB.NET) which loop (for loop or do/while loop) should be used when a counter is required?
Does it make a difference if the loop should only iterate a set number of times or through a set range?
Scenario A - The for loop
for (int iLoop = 0; iLoop < int.MaxValue; iLoop++)
{
//Maybe do work here
//Test criteria
if (Criteria)
{
//Exit the loop
break;
}
//Maybe do work here
}
Advantages
Counter is declared as part of loop
Easy to implement counter range
Disadvantages
Have to use an if to leave the loop
Scenario B - The do/while loop
int iLoop = 0;
do
{
//Increment the counter
iLoop++;
//Do work here
} while (Criteria);
or
int iLoop = 0;
while (Criteria)
{
//Increment the counter
iLoop++;
//Do work here
}
Advantages
Leaving the loop is part of the loop structure
Choice to evaluate before or after loop block
Disadvantages
Have to manage the counter manually
Just for completeness, you could also use option D:
for (int iLoop = 0; Criteria; iLoop++)
{
// work here
}
(where Criteria is "to keep running")
the condition in a for loop doesn't have to involve iLoop. Unusual, though, but quite cute - only evaluates before work, though.
How about the best of both worlds:
for (int iLoop = 0; iLoop < int.MaxValue && !Criteria; iLoop++)
Edit: Now that I think about it, I suppose comparing against int.MaxValue wasn't part of the criteria, but something to emulate an endless for loop, in that case you could just use:
for (int iLoop = 0; !Criterea; iLoop++)
for (int iLoop = 0; iLoop < int.MaxValue && !Criteria; iLoop++) {
//Do work here...
}
Instead of a dummy criteria in the for loop, you can use the actual criteria that you want to use for the loop:
Scenario A2 - the for loop with custom criteria:
for (int iLoop = 0; Criteria; iLoop++) {
// do work here
}
This is equivalent to:
{
int iLoop = 0;
while (Criteria) {
// do work here
iLoop++;
}
}
If you have a loop counter, you should generally use a for loop to make that clearer.
I ususually use for, cause it's simple. I use while when counter is needed after or before loop or if using for is impossible.
You can always add the exit criteria to for loop:
for (int iLoop = 0; iLoop < int.MaxValue && Criteria; iLoop++)
{
//Maybe do work here
}
I would really go for whatever looks most readable in your particular case.
There's no reason not to use a for loop in this case. Even if you have other criteria, it's perfectly valid to write:
for (int iLoop = 0; iLoop < int.MaxValue && Criteria; iLoop++) { ... }
for loops consist of the following:
for ( initialization; condition; action )
you don’t need an extra if to check your criteria, what do you think is i < value? it’s nothing more than a criteria.
i use loops when they fit the problem, there’s no definite answer
Write some test cases and see which works best for you. Have a look a this link: .Net/C# Loop Performance Test (FOR, FOREACH, LINQ, & Lambda)
Personally I would go with the for loop.
It is better to read, more commonly used and very optimized.
for (int iLoop = 0; iLoop < int.MaxValue && !Criteria; iLoop++)
{
// Do Work
}
Edit: int.MaxValue && !Criteria <- a definietely better approach than my initial one ;)
I'd tend to use for if I'm actually using the counter in the loop, say as an index into an array, and as part of the criteria, i.e. "stop at the end of the array" rather than "just don't overflow".
If I'm looping over something with unknown length, such as lines in a file, or just maintaining the counter to use the total after the loop, then I'll use do or while.
However, it really comes down to what's more readable for a particular situation. I expect that you'd struggle to tell from the compiled IL which version was used.
((((difference b/w while and do while--> let me tell you with one example :
if a person going into a hall to fix a bomb inside the hall, he must be checked when getting in.. in another case if a person going into a hall to steal something from there he must have been checked when coming out of the hall.. so based on the process only we have to use our looping condition....))))
The for loop can execute a block of code for a fixed or given number of times.if your counter variable depends on that block of code(means inside the looping condition), you can use the for loop
At least for me i use for() when i need to traverse an array and when no breaking is needed. And do() and while() when i need to process something for an unknown time.