Miha M
Miha M

Reputation: 291

Table with even numbers?

I have code like this to display a table 10 by 10.

I want it to display even numbers between 2 and 10 but I can't make it work.

This table show numbers from 2 to 11 with even and odd numbers. How can I make it to show even only?

This is what I have now:

int[,] table = new int[10, 10];
Random r1 = new Random();
int num8 = 0;
for (int i = 0; i < 10; i++)
{
    for (int j = 0; j < 10; j++)
    {
        tabela[i, j] = r1.Next(2,11);
        if (table[i, j] ==8)
            num8 = num8 + 1;
      }
}

for (int i = 0; i < 10; i++)
{
    for (int j = 0; j < 10; j++)

        Console.Write(table[i, j] + " ");
    Console.WriteLine();
}

Console.WriteLine("In the table we can find: " + num8 + ", number 8.");

Upvotes: 0

Views: 328

Answers (1)

BartoszKP
BartoszKP

Reputation: 35901

The Random.Next method takes an exclusive upper bound. Since you want only even numbers, you can use:

r1.Next(1, 6) * 2

for generating the numbers. r1.Next(1, 6) will give you numbers from the set: 1,2,3,4,5. Doubling the results gives you the following possibilities: 2,4,6,8,10.

Upvotes: 4

Related Questions