Unfrieden - 8 months ago 49

C# Question

My foreach loops one too many times, and I fail to understand why. The program should go trough 1-100 and sum up the fourth power of each digit.

`using System;`

using System.Collections.Generic;

public class Program

{

public static void Main()

{

int sum = 0;

string temp = "";

List<int> digits = new List<int>();

for (long i = 2; i < 100; i++)

{

temp = i.ToString();

for(int y = 0; y < temp.Length; y++)

{

digits.Add(Convert.ToInt32(temp.Substring(y,1)));

foreach(int j in digits)

{

sum += Convert.ToInt32(Math.Pow(j,4));

Console.WriteLine("foreach loop: i = {0}, y = {1}, sum = {2}, j = {3}, digits count = {4}",i,y,sum,j,digits.Count);

}

}

Console.WriteLine("i = {0}, sum = {1}", i, sum);

sum = 0;

digits.Clear();

}

}

}

Below is output example

`foreach loop: i = 10, y = 0, sum = 1, j = 1, digits count = 1`

foreach loop: i = 10, y = 1, sum = 2, j = 1, digits count = 2

foreach loop: i = 10, y = 1, sum = 2, j = 0, digits count = 2

i = 10, sum = 2

foreach loop: i = 11, y = 0, sum = 1, j = 1, digits count = 1

foreach loop: i = 11, y = 1, sum = 2, j = 1, digits count = 2

foreach loop: i = 11, y = 1, sum = 3, j = 1, digits count = 2

i = 11, sum = 3

foreach loop: i = 12, y = 0, sum = 1, j = 1, digits count = 1

foreach loop: i = 12, y = 1, sum = 2, j = 1, digits count = 2

foreach loop: i = 12, y = 1, sum = 18, j = 2, digits count = 2

i = 12, sum = 18

Why does the foreach loop 3 times on a 2 digit number? The digit List is cleared after the loop

Lets take 10 for example.

`temp = "10";`

temp.Length = 2;

second for loop (y) runs twice. 1 < 2

digits gets filled twice

foreach runs three times

Answer Source

Your `foreach`

loop seems create extra loops. It loop all digits in the list every time you adding next digit.

Here you don't even need `foreach`

loop and list of digits too.

```
public static void Main()
{
int sum = 0;
string temp = "";
for (long i = 2; i < 100; i++)
{
temp = i.ToString();
for(int y = 0; y < temp.Length; y++)
{
int digit = Convert.ToInt32(temp.Substring(y,1));
sum += Math.Pow(digit,4);
}
Console.WriteLine("i = {0}, sum = {1}", i, sum);
sum = 0;
}
}
```

I prefer not using strings for handling integers, below is solution without converting between string and integer

```
public static void Main()
{
int sum = 0;
for (long i = 2; i < 100; i++)
{
for(int temp = i; temp > 0; temp /= 10)
{
int digit = temp % 10;
sum += Math.Pow(digit,4);
}
Console.WriteLine("i = {0}, sum = {1}", i, sum);
sum = 0;
}
}
```