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

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;
        }
    }    
}