Reputation: 509
I'm fairly new to C# and I'm doing a school project, i need to figure out how to get a variable or an array with numbers from 1 to 100 without entering every single number in an array for example int[] numbersArray {1,2,3,4,5,6,7,8,9,10...};
because that takes a long time and doesn't look very efficient.
I'm using C# Visual Studio Express 2010. It would mean alot to me if you could answer this for me. I'm gonna be using it in an if statement like so:
if(numbersArray.Contains(numbersInput))
{
Console.WriteLine("numbersInput was a number from 1 to 100")
}
Upvotes: 15
Views: 37520
Reputation: 3680
Other way...
int[] arr = new int[100];
for(int i = 0; i < arr.Length; ++i)
{
arr[i]=i+1;
}
Upvotes: 1
Reputation: 149050
If you're assignment is just to print a message if the input is within a range you simply can do this:
if (numbersInput >= 1 && numbersInput <= 100)
Console.WriteLine("numbersInput was a number from 1 to 100");
But if you really need to create an array with numbers 1..100 you can use a for
-loop:
var numbersArray = new int[100];
for (var i = 1; i <= 100; i++)
numbersArray[i - 1] = i;
Or simply use a little Linq:
var numbersArray = Enumerable.Range(1, 100).ToArray();
Upvotes: 2
Reputation: 3183
you could just use a for loop with the iterator of the loop as the counter:
int[] numbersArray = new int[100] // initialise array to 100 elements.
for (int i = 1; i <= 100; i++)
{
numbersArray[i - 1] = i; // note we are using 0-based indexing to access elements of the array
}
Upvotes: 1
Reputation: 564671
You can use Enumerable.Range
to create a range of numbers:
int[] arr = Enumerable.Range(1, 100).ToArray();
Upvotes: 44