C# C# Collections Lists Lists

Sarah Newton
Sarah Newton
2,178 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

KRIS NIKOLAISEN
PRO
KRIS NIKOLAISEN
Pro Student 51,084 Points

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