C#: Random number generation

This entry is part 65 of 71 in the series C#

In C#, random number is generated using Random.Next method.  Usually we give it a range with a lower and upper limit.

In this example, we also make use of modulus % to arrange the outputs in lines.

This technique of using modulus % to output only 5 numbers in a line is just one of the techniques that we can use for the modulus operator.

using System;

public class RandomNumber
{
    public static void Main()
    {
        Random rnd = new Random();

        Console.WriteLine("\n5 random integers from -100 to 100:");
        for (int ctr = 1; ctr <= 5; ctr++)
        {
            Console.Write("{0,12}", rnd.Next(-100, 101));
            if (ctr % 5 == 0) 
                Console.WriteLine();
        }

        Console.WriteLine("\n10 random integers from 1000 to 10000:");
        for (int ctr = 1; ctr <= 10; ctr++)
        {
            Console.Write("{0,-8}", rnd.Next(1000, 10001));
            if (ctr % 5 == 0) 
                Console.WriteLine();
        }

        Console.WriteLine("\n20 random integers from 1 to 10:");
        for (int ctr = 1; ctr <= 20; ctr++)
        {
            Console.Write("{0,6}", rnd.Next(1, 11));
            if (ctr % 5 == 0) 
                Console.WriteLine();
        }
        Console.ReadKey();
    }
}

random

Series Navigation<< C#: A generic class called Collection
C#: Display all processes running >>