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![](https://ecs-static.teamtreehouse.com/assets/views/marketing/shared/community-banner-white-47072046c51352fe6a69f5e691ff5700b28bb11d45197d7bdf066d9ea3f72d0c.webp)
![Sarah Newton](https://uploads.teamtreehouse.com/production/profile-photos/10478452/micro_T03FJ0NPK-U583CGAET-28a5dee7ce0c-1024.jpg)
Sarah Newton
2,179 PointsI 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.
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
![KRIS NIKOLAISEN](https://secure.gravatar.com/avatar/65d74a723997b41a80d2d909c6e06960?s=96&d=https%3A%2F%2Fecs-static.teamtreehouse.com%2Fassets%2Fcontent%2Fdefault_avatar-445fbbabfc8dc9188fb5967fe43322ee0c3e0dd1e10f378bf8343784af5a13eb.webp&r=pg)
KRIS NIKOLAISEN
54,969 PointsI'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;
}
}
}