# get last number of random array when for loop loop i < 20

Page 1 of 1

## 2 Replies - 5481 Views - Last Post: 02 March 2012 - 11:28 AMRate 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=269120&amp;s=111424a02dcfb045c67b69017015988f&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 2323297

Reputation: 0
• Posts: 2
• Joined: 29-January 11

# get last number of random array when for loop loop i < 20

Posted 02 March 2012 - 09:30 AM

Hello,

When I run my program the first set of 20 numbers print on my console with one extra number (the last number of the sorted array).
The second set of numbers which is the last 20 numbers of the sorted array prints correctly. What am I doing wrong.

```
namespace Sorting
{
class Program
{
static void Main(string[] args)
{
int count;
int[] value = new int[1000];
GetValues(value);
CombSortValues(value);
for (int i = 0; i < 20; i++)
Console.Write("{0}, ", value[i]);
Console.WriteLine(" " + value[value.Length - 1]);
for (int i = 980; i < value.Length - 1; i++)
Console.Write("{0}, ", value[i]);
Console.WriteLine("" + value[value.Length - 1]);

}
static void GetValues(int[] a)
{
Random randomNumber = new Random();
for (int i = 0; i < a.Length; i++)
a[i] = randomNumber.Next(100, 999);
}
public static int[] CombSortValues(int[] a)
{
int gap = a.Length;
double shrink = 1.3;

while (true)
{
if (gap > 1)
{
gap = (int)Convert.ToDouble(gap / shrink);
if (gap == 9 || gap == 10)
{
gap = 11;
}
}
bool isSwapped = false;
for (int i = 0; i + gap < a.Length; ++i)
{
if (a[i] > a[i + gap])
{
int swapValue = a[i];
a[i] = a[i + gap];
a[i + gap] = swapValue;
isSwapped = true;
}
}
if (gap == 1 && !isSwapped)
{
break;
}
}
return a;
```

Is This A Good Question/Topic? 0

## Replies To: get last number of random array when for loop loop i < 20

### #2 sepp2k

• D.I.C Lover

Reputation: 2262
• Posts: 3,467
• Joined: 21-June 11

## Re: get last number of random array when for loop loop i < 20

Posted 02 March 2012 - 09:54 AM

The last value of the array is printed because you do Console.WriteLine(" " + value[value.Length - 1]);. Note that you do that for both for-loops, so in the loop where you print the last 20 elements, the last one will be printed twice.

If you don't want this to happen, remove that line (or replace it with a call to WriteLine without arguments to get a linebreak).

### #3 2323297

Reputation: 0
• Posts: 2
• Joined: 29-January 11

## Re: get last number of random array when for loop loop i < 20

Posted 02 March 2012 - 11:28 AM

It worked! Your explanation was very clear. Thank you for your help.