increment for loop by step 2 in C#?

  • Thread starter Thread starter Rich P
  • Start date Start date
R

Rich P

Basic question: if I need to increment a for loop by step 2 (or step 3,
step 4, ...) -- in VB I say this:

For i = 0 To 10 Step 2
Debug.Print i
Next

Is there an equivalent for C# what does that look like? If there is no
equivalent would I have to do something like this (for the same
example):

for (int i = 0; i < 5; i++)
Console.WriteLine(i * 2)


Rich
 
Rich P said:
Basic question: if I need to increment a for loop by step 2 (or step 3,
step 4, ...) -- in VB I say this:

For i = 0 To 10 Step 2
Debug.Print i
Next

Is there an equivalent for C# what does that look like? If there is no
equivalent would I have to do something like this (for the same
example):

for (int i = 0; i < 5; i++)
Console.WriteLine(i * 2)

for(int i = 0; i < 5; i +=2) /
Console.WriteLine(i)

mick
 
Hello Rich,
Basic question: if I need to increment a for loop by step 2 (or step
3, step 4, ...) -- in VB I say this:

For i = 0 To 10 Step 2
Debug.Print i
Next
Is there an equivalent for C# what does that look like? If there is
no equivalent would I have to do something like this (for the same
example):

for (int i = 0; i < 5; i++)
Console.WriteLine(i * 2)
Rich

i++ increments i by 1, so I think you can do this:

for (int i = 0; i < 11; i += 2)
{
Console.WriteLine(i);
}


Karl
http://unlockpowershell.wordpress.com/
 
thanks all for the replies. I am glad it turned out to be simpler than
I thought it would be.

Rich
 
for (int i = 0; i < 5; i++)
Console.WriteLine(i * 2)


I see you already have the answer, but wanted to share.I saw this in a
program I was fixing recently:

for (int i = 0; i < x.Count; i++)
{
//Do work
i++;
}

Hoepfully that gives someone a Christmas smile.

Peace and Grace,

--
Gregory A. Beamer (MVP)

Twitter: @gbworld
Blog: http://gregorybeamer.spaces.live.com

*******************************************
| Think outside the box! |
*******************************************
 
I see you already have the answer, but wanted to share.I saw this in a
program I was fixing recently:

for (int i = 0; i< x.Count; i++)
{
//Do work
i++;
}

Hoepfully that gives someone a Christmas smile.

More like wondering where my axe is ...

:-)

Arne
 
Try the following code.

int step = 2;
for (int i = 0; i <= 10 ; i+=step)
{
Console.WriteLine(i);
}
 
Back
Top