Mikael Blomkvist
Mikael Blomkvist

Reputation: 149

The do while loop structure

In the do while loop structure usually there's a part where you declare a variable equal to a number (in this case i) and then in a second part you make a increment (i+1). I've made this example in vba, but the structure could be repeated in several different programming languages like the for in php when you're getting data from a database. Now, what I would like to understand better is the relation between the previous mentioned declarations, that is i = some number and i = i + 1 . Wouldn't this generate a problem of interpretation since you're declaring a variable to something and then assigning a different value right after it? Is the second declaration of the variable value, i = i + 1, a new variable calling the previous one or both i's are the same? This is the general orientation I intend with this question. I think explaining the scoop of both variables would help understanding. Thanks!

Sub DoWhile()
Dim x, i, sum
x = 10
i = 1
sum = 0
Do While i < x
sum = sum + i
i = i + 1
Loop
MsgBox “Sum = ” & sum
End Sub

Upvotes: 0

Views: 231

Answers (2)

Jacob Lambert
Jacob Lambert

Reputation: 7679

Since you have created the variable i as a global variable, any reference or modification to i in the sub will be on the same variable. That being said:

Dim i as int

i = 1

Do while i < 11
     MsgBox("The value of i is: " & i)
     i = i + 1
Loop

would display 10 messageboxes showing the value of i being between 1 and 10.

When the program encounters i = i + 1, the computer 'sees' this as take the value of i, add one to it, and store the result in the variable i.

Hope that helps.

Upvotes: 0

Gabe Sechan
Gabe Sechan

Reputation: 93561

A variable is really just a location in memory. That location can have any value. By setting i=i+1, you're really saying "take the value at position i, add 1 to it, and store it at position i". No new variable is created. There's no problem with the computer interpreting this- what it cares about is the location of i, which isn't changing. It still knows where to find i, regardless of how many times you change the value there.

Upvotes: 1

Related Questions