C# C# Collections Lists Lists

Not sure why my answer for this powers challenge is not correct

Here is the task: 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.

using System.Collections.Generic;
namespace Treehouse.CodeChallenges
    public static class MathHelpers
        public static List<int> GetPowersOf2(int value){
            List<int> ints = new List<int>(value + 1);
            for (int i=0; i<ints.Count; i++){
                ints[i]=(int)System.Math.Pow(2, i);

            return ints;

1 Answer

Björn Böning
Björn Böning
9,768 Points

The issue is with two things:

1) You initialize ints with (value +1) and then use ints.Count in the for-header. The issue here is, that ints.Count returns 0 as long as there are no values within the List.

2) You don't add items to a list with ints[i], thats for Arrays. For Lists you should use ints.Add().

So the corrections for your code looks like this:

List<int> ints = new List<int>();

for (int i=0; i < value +1; i++)

ints.Add((int)System.Math.Pow(2, i));