Step n before an operation in a C# for loop - c#

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.

Related

I created a for loop and it doesnt work, but the while loop does, any sugestions?

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.

Setting int using for loop in one line?

I'm interested in doing something like this (C#):
int sum = 0;
for (int i = 0; i < 5; i++)
sum += i;
But I would like to do it on one line. Something like:
int sum = (embedded loop)
Is there any way to do this on one line? I'm looking to apply this to a more complex string manipulation algorithm so I can't simply replace the loop with an arithmatic formula.
So you want to loop and do something in one line?
First off, writing it in one line isn't going to make it run faster. You are still going to loop, you are still going to be O(n). For the particular problem you have in your question you can do something like:
var sum = Enumerable.Range(0,5).Sum();
This will basically make a collection of the numbers 0,1,2...4 and sum them.
More generally, since you want to do something, you might use the Aggregate function. For example:
var str = Enumerable.Range(0,5).Aggregate("",(p,c) => p + c); // Note: not efficient at all
Will take the values 0,1,...4 and do string concatenation with them (using a string builder would be better) to give you the string 01234.
Edit:
I'm trying to loop through a list of words and make each one title case, then return the string[].join(" ") of it
In that case, something like:
var result = string.Join(" ", myListOfWords.Select(w => char.ToUpper(w[0]) + w.Substring(1)));
Should work fine.
If you don't mind that 'sum' only is in scope of the for loop you could do this:
for (int i = 0, sum = 0; i < 5; sum += i, ++i) { // do something }
for(int i=0,sum = 0; i<5; sum+=i,++i){}

confusing "for loop" in c#, when exit the values get cleared

I am just new to c#, please help me understanding for loop in c#..
Issue: I am trying to use j further into my code but after exit out from for loop , it shows j is not exist in the current content.
Is this correct behavior in C# ? how do I get to use j outside the loop?
for (int i = 0; i < 4; i++)
{
int j;
j = 10;
//print j within the loop, which works fine
System.Windows.Forms.MessageBox.Show(j.ToString());
}
//print j outside the loop, which throws error
System.Windows.Forms.MessageBox.Show(j.ToString());
You need to get better acquainted with variable scopes in C# - there is a lot of documentation around if you google it.
As for your code, if you want to access the variable outside the for loop, you need to declare it outside the for loop, e.g.
int j = 0;
for (int i = 0; i < 4; i++)
{
j = 10;
System.Windows.Forms.MessageBox.Show(j.ToString());
}
System.Windows.Forms.MessageBox.Show(j.ToString());
In Your code You declare the variable j inside the loop that's why You cannot able to access the variable.
So declare the variable outside the for loop
just like below,
int j=0; // Declare here
for (int i = 0; i < 4; i++)
{
j = 10;
'print j within the loop, which works fine
System.Windows.Forms.MessageBox.Show(j.ToString());
}
'print j outside the loop, which throws error
System.Windows.Forms.MessageBox.Show(j.ToString());
That's not how C# works.
Your variable j is defined within the scope of the loop. That means it is not accessible from outside the loop.
See the documentation here.
If you want to be able to access the variable from outside the loop, you must declare it from outside the loop as well.
int j;
for (int i = 0; i < 4; i++)
{
j = 10;
}
You cant. its out of scope as you've defined it.
Imagine im the for loop, you gave me the job of doing it.. I think J=10 and make note of it a few times.. i then tell you i did the job.
you then try to use a thing I though of ..
You need to adjust the code.
int j=0;
for (int i = 0; i < 4; i++)
{
j = 10;
'print j within the loop, which works fine
System.Windows.Forms.MessageBox.Show(j.ToString());
}
System.Windows.Forms.MessageBox.Show(j.ToString());
now j exists, inside the loop because it already is made.. so I come and find a postit called "j" and I can write 10 on it. You come back after Im done, the postit is still there.

for loop ends prematurely when objects are removed

Hi I have a problem with a for loop.
It looks like this
for (int i = 0; i < ObjectManager.Instance.Objects.Count; i++)
{
if (ObjectManager.Instance.Objects[i] is Asteroid)
{
ObjectManager.Instance.Objects.Remove(ObjectManager.Instance.Objects[i]);
}
}
But the count gets shorter while I remove objects, which causes the loop to end prematurely. Is there a way to do this without a bunch of extra loops.
Why don't you loop backward?
// Just change the order from Count - 1 down to 0
for (int i = ObjectManager.Instance.Objects.Count - 1; i >= 0; --i)
{
if (ObjectManager.Instance.Objects[i] is Asteroid)
{
ObjectManager.Instance.Objects.Remove(ObjectManager.Instance.Objects[i]);
}
}
In case you have to loop forward (e.g. if Instances should be deleted in the order they are created because they are depend on each other) you can modify for loop in this way:
for (int i = 0; i < ObjectManager.Instance.Objects.Count;) // <- No increment here
if (ObjectManager.Instance.Objects[i] is Asteroid)
ObjectManager.Instance.Objects.Remove(ObjectManager.Instance.Objects[i]);
else
i += 1; // <- Increment should be here!
Yet another possibility is Linq:
ObjectManager.Instance.Objects.RemoveAll(item => item is Asteroid);
Three options:
If ObjectManager.Instance.Objects is a List<T>, use List<T>.RemoveAll with a predicate, making your code much simpler:
// This replaces your whole loop...
ObjectManager.Instance.Objects.RemoveAll(x => x is Asteroid);
Count from the end of the collection rather than from the start, so that you don't need to adjust the index afterwards:
for (int i = ObjectManager.Instance.Objects.Count - 1; i >= 0; i--)
Just decrement i after calling Remove, so that you'll look at the right index on the next iteration.
Note that in the second and third options your code will be a lot simpler to read if you extract the expression ObjectManager.Instance.Objects into a local variable before you use it 4 times. Also consider using RemoveAt(i) rather than Remove(instances[i]), assuming RemoveAt is available for the type you're using.

How can I use a for or while loop with an int declared outside the body?

I have a loop, like so:
for (i < splitted.Length; i++ != 0)
{
key += '\\' + splitted[i];
}
Depending on an if condition above, i, decdlared outside of the loop's body, may need to be incremented (I am splitting a string into a string[] and then need to join parts of it, but maybe from the 5th index, 6th, etc, depending on the condition in the if clause).
However, C# does not let me write a loop like the above. Can I have a loop like the above?
Thanks
You can have an empty initialization clause to allow assignment outside of the for loop:
int i = 0;
for ( ; i < 10; ++i)
Console.WriteLine(i);
for (;i < splitted.Length; i++)
{
if (i!=0)
key += '\\' + splitted[i];
}
A for statement in C# has 3 parts (initializer, condition, and iterator) which are separated by ;.
for (initializer; condition; iterator)
Any of these parts can be empty. The syntax you are giving is only specifying 2 parts and is hence giving a compilation error. Since the variable is declared outside the loop you want to skip the initializer by leaving it empty
for (; i < splitted.Length; i++)

Categories

Resources