0

In my code i have static int method that should return an array of random integers. The problem is when i print an array, only the last number is random int, and other ints are all zeros.

static void Main(string[] args)
{
    int a = int.Parse(Console.ReadLine());
    int[] array = mtd(a);
    for (int i = 0; i < array.Length; i++)
    {
        Console.WriteLine(array[i]);
    }
}
public static int[] mtd(int b)
{
    int[] arr = new int[b];
    Array.Resize<int>(ref arr, b);
    Random rand = new Random();
    for (int i = 0; i < arr.Length; i++)
    {
        arr.SetValue(rand.Next(1, 5), arr.Length - 1);
    }
    return arr;
}
1
  • 2
    Did you set breakpoints, step through the code, inspect your variables and look at the documentation for Array.SetValue() so you can confirm that this code does what you expect it to? Hint: you're not using i... Commented Jun 27, 2016 at 6:58

3 Answers 3

3

In the for loop in your method mtd you are always setting the last value of your array arr by using arr.Length - 1. Use i instead:

for (int i = 0; i < arr.Length; i++)
{
    arr[i] = rand.Next(1, 5);
}

Or with arr.SetValue:

for (int i = 0; i < arr.Length; i++)
{
    arr.SetValue(rand.Next(1, 5), i);
}
Sign up to request clarification or add additional context in comments.

2 Comments

okay, i get it now, so the problem was my array.resize line. I was trying to use "i" but it could not work back then.
You didn't need to use Array.Resize because you were setting the size of the array before when using new int[b].
0

Working one :

public static int[] mtd(int b)
    {
        int[] arr = new int[b];
        Random rand = new Random();
        for (int i = 0; i < arr.Length; i++)
        {
            arr.SetValue(rand.Next(1, 5), i);
        }
        return arr;
    }

EDIT : Btw the Array.resize is useless here, you already define the length of your array. ( new int[b] set the length of the array to b )

Your problem was that you never used i, so you just set the value of the last value of your array.

Comments

0

I modified and simplified your code:

    public static int[] mtd(int b)
    {
        int[] arr = new int[b];
        Random rand = new Random();
        for (int i = 0; i < arr.Length; i++)
            arr[i] = rand.Next(1, 5);
        return arr;
    }

2 Comments

arr[i] = rand.Next(1, 5) does look much better.
Thank you. @Adi543.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.