C# Random Next(Int32, Int32)

Description

Random Next(Int32, Int32) returns a random integer that is within a specified range.

Syntax

Random.Next(Int32, Int32) has the following syntax.


public virtual int Next(
  int minValue,
  int maxValue
)

Parameters

Random.Next(Int32, Int32) has the following parameters.

  • minValue - The inclusive lower bound of the random number returned.
  • maxValue - The exclusive upper bound of the random number returned. maxValue must be greater than or equal to minValue.

Returns

Random.Next(Int32, Int32) method returns A 32-bit signed integer greater than or equal to minValue and less than maxValue; that is, the range of return values includes minValue but not maxValue. If minValue equals maxValue, minValue is returned.

Example

The following example uses the Random.Next(Int32, Int32) method to generate random integers with three distinct ranges.


//from  www  .  j  a  v a  2  s.  co  m
using System;

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

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

      Console.WriteLine("\n20 random integers from 1000 to 10000:");      
      for (int ctr = 1; ctr <= 20; 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();
      }
   }
}

The code above generates the following result.

Example 2

The following example generates a random integer that it uses as an index to retrieve a string value from an array. Because the highest index of the array is one less than its length, the value of the Array.Length property is supplied as a the maxValue parameter.


using System;/* ww w .j a v  a  2s .  com*/

public class Example
{
   public static void Main()
   {
      Random rnd = new Random();
      string[] malePetNames = { "A", "B", "C", "D", 
                                "E", "F", "G", "H", 
                                "I", "J" };

      int mIndex = rnd.Next(0, malePetNames.Length);
      Console.WriteLine(malePetNames[mIndex]);

   }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version