简体   繁体   中英

C# variable or array with number range (example. 1 - 100)

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")
}

您可以使用Enumerable.Range创建一系列数字:

int[] arr = Enumerable.Range(1, 100).ToArray();

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();

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
}

Other way...

int[] arr = new int[100];
for(int i = 0; i < arr.Length; ++i)
{
    arr[i]=i+1;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM