Im trying to write a c# programme that will generate a random number, check if this number is in my array, if it is, repeat generate number step, else insert this number into slot [i] of my array.

Here is my code so far - Any help would be greatly appreciated! :)

        int check=0, lottoCheck;


        Random rand = new Random();

        int[] lotto = new int[6];



  //Need while loop wrapped around this - parameters something like -while x < filled slot lotto arrays. cant think of how to write this :(

            for (int i = 0; i < lotto.Length; i++) // this will limit the loop to only 6 - must change!
            {
                check = rand.Next(1, 41);
                Console.WriteLine("Random number to be checked is -> "+check);

                if (lotto.Contains(check))
                {
                   lotto[i] = check;
                }

                 Console.WriteLine("slot " + i + " contains " + check);
              }

You could handle the increment of i inside the for-loop like so:

for(int i = 0; i < lotto.Length; )
{
    check = rand.Next(1, 41);
    Console.WriteLine("Random number to be checked is -> "+check);

    if (lotto.Contains(check))
    {
        //You could do another WriteLine() here.
    }
    else
    {
        //Only add check and increment i if it does not contain check.
        lotto[i] = check;
        Console.WriteLine("slot " + i + " contains " + check);
        i++;
    }
}

So you'd only increment i, if the random number is not contained in the list.

Using a for loop is a bad practice, use a while loop

int i = 0;
while (i < lotto.Length) {
    check = rand.Next(1, 41);
    if (lotto.Contains(check) == false) {
        lotto[i] = check;
        i++;
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.