Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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