How can I generate a random integer in C#?
How can I generate a random integer in C#?
I completed my post-graduation in 2013 in the engineering field. Engineering is the application of science and math to solve problems. Engineers figure out how things work and find practical uses for scientific discoveries. Scientists and inventors often get the credit for innovations that advance the human condition, but it is engineers who are instrumental in making those innovations available to the world. I love pet animals such as dogs, cats, etc.
Aryan Kumar
13-Jul-2023Sure, here is how you can generate a random integer in C#:
C#
This code first creates a
Randomobject. TheRandomobject is used to generate random numbers.The code then generates a random integer between 0 and 100. The
Next()method of theRandomobject is used to generate a random number. TheNext()method takes a maximum value as a parameter. The maximum value is exclusive, so the random number will be between 0 and the maximum value - 1.Finally, the code prints the random integer to the console.
Here is an explanation of the code:
usingstatement is used to import theSystemnamespace. TheSystemnamespace contains theRandomclass.Randomclass is used to generate random numbers.Next()method of theRandomclass is used to generate a random number.Console.WriteLine()method is used to print a string to the console.