C# C# Collections Lists Lists

Justin Cure
Justin Cure
5,001 Points

Code compiles correctly, but list returned does not contain the correct number of items?

Trying to complete the GetPowersOf2 coding challenge in the C# Collections module on Lists, and I can't get my code to return a list with the correct number of items. The code compiles, and I believe I'm calculating the expected results correctly, but I'm not sure why it's not populating the correct number of items. My for loop iterates from 0 to the value passed in to the GetPowersOf2 method, so I don't see what the problem is.

MathHelpers.cs
using System.Collections.Generic;
using System;

namespace Treehouse.CodeChallenges
{
    public static class MathHelpers
    {
        public static List<int> GetPowersOf2(int value)
        {
            List<int> powersOf = new List<int>();
            double val = 2;
            for(var i = 0; i < value; i++)
            {
                double result = Math.Pow(val, i);
                int power = Convert.ToInt32(result);
                powersOf.Add(power);
            }
            return powersOf;
        }

    }
}

1 Answer

andren
andren
28,343 Points

My for loop iterates from 0 to the value passed in to the GetPowersOf2 method, so I don't see what the problem is.

Since the condition for your loop is i less than value the loop will not run when i is actually equal to the value passed in. So if 4 is passed in it will only calculate the power up to 3.

If you change your condition to less than or equal to like this:

using System.Collections.Generic;
using System;

namespace Treehouse.CodeChallenges
{
    public static class MathHelpers
    {
        public static List<int> GetPowersOf2(int value)
        {
            List<int> powersOf = new List<int>();
            double val = 2;
            for(var i = 0; i <= value; i++) // Changed < to <=
            {
                double result = Math.Pow(val, i);
                int power = Convert.ToInt32(result);
                powersOf.Add(power);
            }
            return powersOf;
        }

    }
}

Then your code will work.

Justin Cure
Justin Cure
5,001 Points

This worked! Thank you for your help.