I am tryig to solve a algorithm example. There will be a array.And i need to calculate the square of this arrays index numbers. Output should be:"0-1-4-9-16-25-36-49-64-81" since the index numbers starts with 0-9.
I searched on the web.But i couldnt find anything.I think we need to declare an array like this:
int[] a = new int[10];
But i dont know what to do after that.Should we take input from user or not?
If anyone knows python, this is the python code:
from numpy import
indis = arrange(0,10)
for dizi in indis:
dizi=dizi**2
print(dizi, end=" ")
Thank you for your help.
for(int i=0; i<10; i++){
Console.WriteLine(i*i);
}
How about this - its more like the python
var sq = Enumerable.Range(0,9).Select(x=>x*x).ToArray();
foreach(var s in sq)
Console.WriteLine(s);
or maybe
var sq = Enumerable.Range(0,9).ToArray();
foreach(var s in sq)
Console.WriteLine(s*s);
this is even closer to the python
Since you obviously move from Python to C#, let's start with a bit of Python (probably the first time I write code with this language...).
Here, what I found out so far:
range()
thing, which may or may not be optimized away.Because of 2., you do not clearly see the problem at hand and as such, you lack to see the obvious optimization when you transfer to C#. There (in C#), no one in their right mind would create a temporary data structure (eg an array) with a consecutive number of integers and then iterate over it. This would be wasteful and obscure on many levels.
So, with the restrictions of Python, trying to avoid the range()
overhead, you would probably write:
def meh(arr):
i = 0
while i < len(arr):
print(i*i)
i = i + 1
Of course, the argument arr
above would be a list, not an array because of 1.
And if you translate that bit of (optimized) code to C#, it looks something like:
void meh<T>(T[] arr) {
for (int i = 0; i < arr.Size; i++) {
print(i*i)
}
}
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.