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.
CodePudding user response:
for(int i=0; i<10; i ){
Console.WriteLine(i*i);
}
CodePudding user response:
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
CodePudding user response:
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:
- Python has no (built in) arrays. That NumPy thing must be a library of sorts.
- The for loop of Python is quite restricted. "Normal" idioms do not exist.
But there is the rather obscure (unless Python is lazy like Haskell)
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 (e.g. 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)
}
}
CodePudding user response:
int[] a = new int[10];
for (int i = 1; i <= 9; i )
{
a[i] = (i * i);
Console.WriteLine(a[i]);
}