Toni
Toni

Reputation: 3

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

Upvotes: 0

Views: 1313

Answers (4)

tym32167
tym32167

Reputation: 4881

Why soo commplicated?

for (int n = 100; n < 1000; n++)
{
    var s1 = n/100 % 10;
    var s2 = n/10 % 10;
    var s3 = n/1 % 10;

    var sum = s1+s2+s3;
    if (sum == 9)
    Console.WriteLine(n);       
}

For people, who dont like easy way :D

Enumerable.Range(0, 1000).Select(x => x.ToString())
    .Where(x => x.Length == 3).Select(x => new {x, sum=x.ToCharArray()
    .Select(c=>int.Parse(c.ToString())).Sum()}).Where(x=>x.sum == 9)
    .Select(x=>x.x).ToList().ForEach(Console.WriteLine);    

Oki, tried to create non-generic but fastest solution.

for (var i = 1; i <= 10; i++)
    for (var j = 0; j < 10; j++)
    {
        if ((i>1 && j == 0) || i < j)           
        {                   
            Console.WriteLine(i * 90 + j * 9);              
        }
    }

Upvotes: 2

Avneesh Srivastava
Avneesh Srivastava

Reputation: 437

I think you are looking for this:

    class Program
{
    static void Main(string[] args)
    {

        for (int n = 100; n < 1000; n++)
            {
                int sum = 0;
                int num = n;
                while (num != 0)
                {
                    int r = num % 10;
                    sum += r;
                    num /= 10;
                }
                if (sum == 9)
                    Console.WriteLine(n);//.....Number whose all digit sum ==9
            }
    }
}

Upvotes: 0

Everyone
Everyone

Reputation: 1825

You're not resetting sum after every loop iteration. sum should equal zero at the start of every iteration like. Also, the while loop is wrong. Try this:

for(int n=100;n<1000;n++)
        {
            sum=0;
            int i = n;
            while(i!=0) {
                sum += i % 10;
                i /= 10;
            }
            if (sum == 9)
            Console.WriteLine("Number {0} has digit sum of {1}", n, sum);
        }

Upvotes: 2

Tim Schmelter
Tim Schmelter

Reputation: 460098

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

Upvotes: 3

Related Questions