C# C# Collections Lists Lists

C# Collections

Lost, please point me in the right direction, thanks.

Question: Create a static method named GetPowersOf2 that returns a list of integers of type List<int> containing the powers of 2 from 0 to the value passed in. For example, if 4 is passed in, the method should return this list of integers: { 1, 2, 4, 8, 16 }. The System.Math.Pow method will come in handy.

Link: https://teamtreehouse.com/library/c-collections/lists/lists-2

One of my many attempted answers: namespace Treehouse.CodeChallenges { public static class MathHelpers { public static List<int> GetPowersOf2(int input) { var returnList = new List<int>(); for (int i = 0; i < input + 1; i++) { returnList.Add((int)System.Math.Pow(2, i)); } return returnList;

    }

}

}

MathHelpers.cs
namespace Treehouse.CodeChallenges
{
    public static class MathHelpers
    {
        public static List<int> GetPowersOf2(int input)
        {
            var returnList = new List<int>();
            for (int i = 0; i < input + 1; i++)
            {
                returnList.Add((int)System.Math.Pow(2, i));
            }
            return returnList;

        }

    }
}

3 Answers

Steven Parker
Steven Parker
171,904 Points

Check the "preview" button when you have compile issues.

In this case, you would have seen a message reminding you that you had forgotten to include a line like this in your file:

using System.Collections.Generic;

That's the namespace that "List" is defined in.

S.Amir Nahravan
S.Amir Nahravan
4,007 Points

You can use this code

using System.Collections.Generic; namespace Treehouse.CodeChallenges { public static class MathHelpers { public static List<int> GetPowersOf2(int powers) { List<int> result = new List<int>(); int po; for(int i=0; i<=powers; i++) { po = (int)System.Math.Pow(2,i); result.Add(po); } return result; } } }

Yeah, I found that. I couldn't figure out how to get back to this help question to place a "Never mind, I figured it out" message. Thanks for the help though.