Cosmin Manea
Cosmin Manea

Reputation: 5

Method that returns a new array where each element is the square or the original element

I'm trying to get an array of N numbers and then print them. I receive this error. I looked at some examples but I don't know what is wrong:

{
        int[] myArray = new int[] { 1, 2, 3 };

        //for (int i = 0; i < myArray.Length; i++)
        //{
        //    Console.WriteLine(Math.Pow(myArray[i],2));
        //}
    }

    private static int squareArray(int[] array)
    {
        int[] result = new int[array.Length];
        for (int i = 0; i < array.Length; i++)
        {
            result[i] = Math.Pow(array[i], 2);
        }
        return result;
    }

Upvotes: 0

Views: 3456

Answers (1)

Tamas Ionut
Tamas Ionut

Reputation: 4410

Try this:

private static int[] squareArray(int[] array)
{
    int[] result = new int[array.Length];
    for (int i = 0; i < array.Length; i++)
    {
        result[i] = (int)Math.Pow(array[i], 2);
    }
    return result;
}

or you can do it simpler like this:

var squaredArray = array.Select(x=>x*x).ToArray();

Upvotes: 2

Related Questions