0
For y = 1 to 10 
y = y+1
print(y)
Next

For the above code the output which I get is 2,4,6,8,10. Shouldn't the o/p be 2,3,4,5,6,7,8,9,10 Can I consider y = y+1 as y++

Vinu
  • 3
  • 1
  • 4

4 Answers4

4

The default step increment for a vbscript for loop is 1. By adding in y=y+1, you are effectively increasing your increment by 2 each cycle:

 For y = 2 to 10 step 2
     Wscript.echo y
 Next

There is no "increment operator" as such; However you could consider step an increment operator in this context (both positive and negative).

y = y + 1 is similar as the intended concept y++.

You would probably be best using that type of operation inside a do/while loop where there are no auto increments eg:

y = 0
do while y < 10
  y = y + 1
  wscript.echo y
Loop

See this previous post: Does VBScript have Increment Operators

Community
  • 1
  • 1
Damien
  • 1,490
  • 1
  • 8
  • 17
0

in a For...Next loop, you won'T need to increase the counter value manualy.

Eddynand Fuchs
  • 344
  • 1
  • 13
0

No, VB Script doesn't have an increment operator. VB script is based on BASIC which is a language meant for learning and the increment operator is considered to be confusing by many so it was never added on purpose.

As for your second question, to get the output you want remove y = y+1 line and change loop to For y = 2 to 10. Also, yes, y=y+1 is the same as y++ in most languages.

krowe
  • 2,129
  • 17
  • 19
  • `For Loop` does have `Step` (as demostrated by Damien) – Pankaj Jaju Feb 13 '14 at 15:53
  • @PankajJaju Not sure how the Step operator helps answer this. It is completely an optional operator. The OP code shows how you can easily make the same code without it. – krowe Feb 13 '14 at 15:57
  • http://stackoverflow.com/questions/971312/why-avoid-increment-and-decrement-operators-in-javascript – Damien Feb 13 '14 at 16:06
  • @krowe - I was just saying that `For Loop` does have a incremental operator ... not saying that your answer is incorrect or not. Just disagreed with the first statement. – Pankaj Jaju Feb 13 '14 at 16:12
0

You are increasing the value that is increased by the For loop:

For y = 1 to 10 ' starts at 1, next is 3
y = y+1         ' but you increase it to 2, increased to 4
print(y)        ' prints 2, 4
Next            ' Increases to 3, 5, up to 11, then stops because it's greater than 10
John Saunders
  • 160,644
  • 26
  • 247
  • 397