Page 1 of 1

Working with arrays in VB6 Adding at different positions in an array, sorting them in ascending/d Rate Topic: -----

#1 Nikhil_07n  Icon User is offline

  • The cheese stands alone..
  • member icon

Reputation: 54
  • View blog
  • Posts: 2,490
  • Joined: 09-January 09

Posted 21 January 2009 - 10:39 PM

First of all we have declared the array, it contains 10 elements(0 to 9).

 Dim arr(9) As Single

Add the numbers in any manner you wish, the best is here.

Private Sub cmdAddAll_Click()
For i = 0 To 9
arr(i) = InputBox("enter a no.")
Next i
End Sub

Adding Number at different positions

Private Sub cmdAddatPos_Click()
no = InputBox("no to enter")
pos = InputBox("position")
For i = 9 To pos Step -1
arr(i) = arr(i - 1)
Next i
arr(pos - 1) = no
End Sub

Explaination : no is a varaible in which the desired no is stored.
pos is a variable in which we are storing the position of entering.

Now , the elements of aray above the position are unaffected, all we are doing is that we are Shifting the elements below the desired position by one place. For ex. the element at position 9 is erased and in takes the value of element 8.

Now, After shifting we are entering the desired number(no) in the required position.
NOTE: (pos-1) is used because the array starts with 0.

Sorting in Ascending Order

Private Sub cmdAscending_Click()
For k = 0 To 8
For j = k + 1 To 9
If arr(j) < arr(k) Then
a = arr(j)
arr(j) = arr(k)
arr(k) = a
End If
Next j
Next k

This one is the best example for understanding nested loops.
The outer loop selects one element for comparing.
The inner loops starts with the next element and compares it with the outer loop element.

If outerloop element is GREATER then inner loop element, their positions are interchanged, otherwise nothing is done.

at the end of both loops the the array gets sorted in ascending order.

Just print the array to see what happens:

For i = 0 To 9
Picture1.Print arr(i)
Next i
End Sub

Hope this helped you understand the concept of loops and arrays.

Is This A Good Question/Topic? 1
  • +

Page 1 of 1