increment for loop by step 2 in C#?


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
 
Ad

Advertisements

M

mick

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
 
K

Karl Mitschke

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/
 
J

Jeremy McPeak

for (int ii = 0, foo = 0; (foo = 2 * ii) < 5; ii++

Console.WriteLine(foo)
}
 
R

Rich P

thanks all for the replies. I am glad it turned out to be simpler than
I thought it would be.

Rich
 
G

Gregory A. Beamer

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! |
*******************************************
 
Ad

Advertisements

A

Arne Vajhøj

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
 
Ad

Advertisements

Joined
Jul 13, 2017
Messages
1
Reaction score
0
Try the following code.

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top