C# - Generate Random Numbers

In this example, we are going to learn how to generate random numbers using C# program?
Submitted by Nidhi, on August 17, 2020 [Last updated : March 22, 2023]

Here, we used Random class to generate random numbers using the Next() method of the random class.

C# program to generate random numbers

The source code to generate random numbers in C# is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//Program to Generate Random Numbers in C#.

using System;

class RandomEx
{
    static void Main()
    {
        int num = 0;
        Random R = new Random();

        Console.WriteLine("Random Numbers: ");
        for (int i = 1; i < 10; i++)
        {
            num = R.Next();
            Console.WriteLine(num);    
        }
    }
}

Output

Random Numbers:
1396315331
747908140
1390110439
2025904104
318255387
1630415135
455253731
1489207714
137356946
Press any key to continue . . .

Explanation

In the above program, we created the RandomEx class that contains Main() method, In the Main() method we created the object R of Random class.

Console.WriteLine("Random Numbers: ");
for (int i = 1; i < 10; i++)
{
    num = R.Next();
    Console.WriteLine(num);    
}

Here we used the Next() method to generate random numbers and then print them on the console screen.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.