Initialize an Int array with a range of numbers in C#
This post will discuss how to initialize an Int array with a range of numbers in C#.
1. Using Enumerable.Range Method
The standard solution to generate a sequence of numbers within a specified range is using the Enumerable.Range method from System.Linq namespace. It takes the starting value of the sequence and the number of sequential integers to generate. The following example demonstrates its usage.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Linq; public class Example { public static void Main() { int m = 1; int n = 10; int[] array = Enumerable.Range(m, n - m + 1).ToArray(); Console.WriteLine(String.Join(", ", array)); } } |
Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
2. Using For Loop
A faster solution is to create a new array of the required size and use a traditional for-loop to fill up the array, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; public class Example { public static void Main() { int m = 1; int n = 10; int[] array = new int[n - m + 1]; for (int i = 0; i < array.Length; i++) { array[i] = m++; } Console.WriteLine(String.Join(", ", array)); } } |
Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
That’s all about initializing an Int array with a range of numbers in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)