What's the Best Way to Do a Backwards Loop in C/C#/C++

What's the best way to do a backwards loop in C/C#/C++?

While admittedly a bit obscure, I would say that the most typographically pleasing way of doing this is

for (int i = myArray.Length; i --> 0; )
{
//do something
}

How to reverse for loop in c# for string type ? i need to remove one character each iteration

it's ok now

for (int i = 4; i > 0; i--)
{
for (int j = 1; j <= i; j++)
Console.Write("*");
Console.WriteLine();
}

Possible to iterate backwards through a foreach?

When working with a list (direct indexing), you cannot do it as efficiently as using a for loop.

Edit: Which generally means, when you are able to use a for loop, it's likely the correct method for this task. Plus, for as much as foreach is implemented in-order, the construct itself is built for expressing loops that are independent of element indexes and iteration order, which is particularly important in parallel programming. It is my opinion that iteration relying on order should not use foreach for looping.

strange behavior of reverse loop in c# and c++

You declared the int as unsigned. It will always be >= 0. The only reason you see negative values is that your printf call interprets it as signed (%d) instead of unsigned (%ud).

C# Understanding how to walk a string backwards

Take this example.

string target = "ABC";
// target can be thought of as an array of characters
// target[0] holds 'A'
// target[1] holds 'B'
// target[2] holds 'C'

int length = target.Length;
// length would be 3 because Length is the count of the chars
// but if you were to try and get the value of target[3] you would get an error
// because target ends at [2] (index 2)

So you need to start at .Length - 1 and work backwards to 0 (not 1).

In C# .NET 2.0, what's an easy way to do a foreach in reverse?

I'd use a SortedList instead of a dictionary. You can still access it by Key, but you can access it by index as well.

SortedList sCol = new SortedList();

sCol.Add("bee", "Some extended string matching bee");
sCol.Add("ay", "value matching ay");
sCol.Add("cee", "Just a standard cee");

// Go through it backwards.
for (int i = sCol.Count - 1; i >=0 ; i--)
Console.WriteLine("sCol[" + i.ToString() + "] = " + sCol.GetByIndex(i));

// Reference By Key
foreach (string i in sCol.Keys)
Console.WriteLine("sCol[" + i + "] = " + sCol[i]);

// Enumerate all values
foreach (string i in sCol.Values)
Console.WriteLine(i);

It's worth noting that a sorted list stores key/value pairs sorted by key only.



Related Topics



Leave a reply



Submit