Toni Toni - 22 days ago 5
C# Question

C# Sum of digits of a number if the sum equals 9

i want all the numbers with 3 digits that have the sum of 9 to be write in the console.
This is what i came up so far and it doesnt work:

class Program
{
static void Main(string[] args)
{
int sum = 0;
for (int n = 100; n < 1000; n++)
{
while (n <1000)
{
sum += n % 10;
n /= 10;
if (sum == 9)
Console.WriteLine(sum);
}
}
}
}

Answer

I'd use three loops, one for every digit:

for (int i1 = 1; i1 < 10; i1++)
for (int i2 = 0; i2 < 10; i2++)
for (int i3 = 0; i3 < 10; i3++)
{
    if (i1 + i2 + i3 == 9)
        Console.WriteLine("{0}{1}{2}", i1, i2, i3);
}