Page 1 of 1

## Working with arrays in VB6 Adding at different positions in an array, sorting them in ascending/d Rate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=82134&amp;s=89cf34e74758ade9f64fd2a0232dba71&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 Nikhil_07n

• The cheese stands alone..

Reputation: 54
• 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

```

Explanation:
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

 .related ul{list-style-type:circle;font-size:12px;font-weight:bold;}.related li{margin-bottom:5px;background-position:left 7px!important;margin-left:-35px;}.related h2{font-size:18px;font-weight:bold;}.related a{color:blue;}