2

I'm new to programming so please bear with me!

I am trying to set the parts of an array to random values, but whenever I run the program it sets all parts of the array to the same value. I want them all to be different.

Here is my code:

int[] hello_array = new int[10];
        Console.WriteLine("Here");

        Random rndm = new Random();

        for (int j = 0; j < hello_array.Length; j++)
        {
            hello_array[j] = rndm.Next(99);
        }

        Console.WriteLine("Now Here");

        for (int i = 0; i < hello_array.Length; i++)
        {
            Console.WriteLine("hahahaha look at this " + hello_array[0]);

I'm probably completely missing it, but I can't tell what's wrong with my code! Can someone please tell me how I would make it so that all ten parts of the array generate different random numbers?

Tariqulazam
  • 4,535
  • 1
  • 34
  • 42

2 Answers2

9

Change this:

 Console.WriteLine("hahahaha look at this " + hello_array[0]);

to this:

 Console.WriteLine("hahahaha look at this " + hello_array[i]);

You were printing the same element in the array on every loop.

Matt Burland
  • 44,552
  • 18
  • 99
  • 171
1

With the same number of lines, you could use some of the newer C# features to accomplish the same result (but without all the messy details).

You'd define a generic method that takes two parameters: a lambda expression (for instance, () => random.Next(99)) and the number of elements to generate. Inside the method, you'd use the yield keyword to return a new element generated by the factory.

Random random = new Random();
foreach (var element in Generate(() => random.Next(99), 10))
{
    Console.WriteLine(element);
}

public static IEnumerable<T> Generate<T>(Func<T> factory, int elements)
{
    for (int generated = 0; generated < elements; generated++)
    {
        yield return factory();
    }
}
Community
  • 1
  • 1
Adam
  • 15,537
  • 2
  • 42
  • 63
  • A little overkill for such a simple example, I think. If you're going to rewrite it, why not just use: `for (int i = 0; i < 10; i++) { Console.WriteLine("hahahaha look at this " + rndm.Next(99)); }` :P – Richard Marskell - Drackir Oct 31 '12 at 15:14