Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,526 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.