C# – Add all natural numbers that are multiples of 3 and 5 : What is the bug in the following code

c

I know that this can be easily done by using

if(i%5 == 0 OR i%3 ==0) sum+=i;

But what is wrong in the following C#code:

    int sum = 0;
    for(int i = 0, j = 0; i < 1000; i+=3, j+=5)
    {
        Console.WriteLine("i = " + i);
        Console.WriteLine("j = " + j);

        sum += i;

        Console.WriteLine("Sum after adding i  = " + sum);

        if(j < 995 && j % 3 != 0)
        {
            sum += j;
        }

        Console.WriteLine("Sum after adding j  = " + sum);

    }

Best Answer

The statement j < 995 should probably be j <= 995, otherwise you are not going to add 995 to your sum.