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

Sarah Newton
Sarah Newton
2,179 Points

I don't understand what is going wrong here.

Looks as though the foreach loop runs as expected and the add function runs but don't understand why nothing is being added to the list. Haven't used the Math.Pow much before so wondering if I'm using correctly.

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

namespace Treehouse.CodeChallenges
{
    public static class MathHelpers
    {
        public static List<int> GetPowersOf2(int value) {
            List<int> items = new List<int>(value);
            List<int> powers = new List<int>();
            foreach (int item in items)
            {
                int count = 0;
                double powerCalc = System.Math.Pow(2, count);
                powers.Add(Convert.ToInt32(powerCalc));
                count++;
            }
            return powers;
        }
    }    
}

1 Answer

I'm not sure how to get foreach to work. In your code you have two issues: You set count = 0 in the loop so for each iteration it has a value of 0. And your items list should have a size of value + 1 (goes from zero to the number entered - the instructions give the example of 4 entered returning a list of 5 values).

I was able to do it with a for loop though:

using System;
using System.Collections.Generic;

namespace Treehouse.CodeChallenges
{
    public static class MathHelpers
    {
        public static List<int> GetPowersOf2(int value) {
            List<int> powers = new List<int>();

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

                double powerCalc = System.Math.Pow(2, i);
                powers.Add(Convert.ToInt32(powerCalc));

            }
            return powers;
        }
    }    
}