-1
Dim i as Long, arr(5) As Long

for i = 1 to 6
    arr(i-1) = i-1
next 
console.writeLine(arr(LBound(arr)+5) + arr(UBound(arr)-2))

I understand the output is 8 but could someone explain why it is 8, Lbound and UBound, this type of question comes up in my exam, and i am having some issue with getting my head around this.

Much appreciated

loco3424
  • 23
  • 2
  • 6
  • A short little google about `vb.net ubound` gave me on the second link (this may vary at your computer) the microsoft documentation of the function UBound. – muffi Mar 20 '19 at 12:23
  • `Console.WriteLine(arr(LBound(arr) + 5) + arr(UBound(arr) - 2))` will equal 8 as `lbound(arr) = 0 + 5 and ubound(arr)` = 5 - 2 = 3. lbound gets left most number in array so be 0 in your case and you added a 5 and Ubound gets the highest bascailly so be a 5 - 2 and finally add the results together = 5 + 3 = 8! – K.Madden Mar 20 '19 at 12:29
  • In `arr(LBound(arr)) => arr(0)` you put `0 => (1 -1)` Then add `5 => (0 + 5)`. In `arr(UBound(arr)) => arr(5)` you put `5 => (6 - 1)`. Then, you subtract `2 => (5 - 2)`. So you have `(0 + 5) + (5 - 2)`. – Jimi Mar 20 '19 at 12:30

1 Answers1

2

UBOUND means "Upper Boundary" in VB. It returns the sequence number for the last item (the upper boundary) of an array. LBOUND is for the lower boundary or first item.

I don't typically use them these days as VB.Net has easier to use options to do the same thing.

your loop builds this array

arr(0)=0 
arr(1)=1 
arr(2)=2 
arr(3)=3 
arr(4)=4 
arr(5)=5

Now LBound(arr) here returns 0, and the ubound(arr) returns 5.

now, if you array was this:

arr(0)=10
arr(1)=11
arr(2)=12
arr(3)=13
arr(4)=14
arr(5)=15

Then LBound(arr) still returns 0, and the ubound(arr) returns 5.

UBOUND FUNCTION

LBOUND FUNCTION

K.Madden
  • 353
  • 1
  • 16
Stephen Wrighton
  • 36,783
  • 6
  • 67
  • 86
  • Very good explanation and example! may i suggest add in 2 references for future users! UBOUND: https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/ubound-function LBOUND: https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/lbound-function – K.Madden Mar 20 '19 at 12:36