1

I have a small problem. My code is this one :

int c = 0;
int i = 0;
int a = 28;
while (i < a) {
    i++;
    if (i % a == 0) {
        c += i;
        Console.WriteLine(i.ToString());
    }
}

Why does the string i is displayed only once, after the end of the while ? It should be displayed a times.

Your help will be appreciated !

2
  • 4
    Step through this with the debugger. Commented Dec 3, 2013 at 21:10
  • You are playing with the perfect number 28. You are trying to sum up all numbers i that divide 28, but because you put the operands in the wrong order, you sum all numbers i that 28 divides. Commented Dec 3, 2013 at 21:35

3 Answers 3

5

Your if condition is opposite it should be:

 if (a % i == 0)

Currently you are trying to do remainder division with i % a and it will only meet the condition when i reaches 28, so you get the output once.

Sign up to request clarification or add additional context in comments.

Comments

0

% is for modulus division, which basically divides by the number and gives you back the remainder. When you're loop reaches 28 it divides it by 28 and the resulting remainder is 0. This only happens once "when your loop reaches 28".

Comments

0

It would help if you told us what was printed out. I guess it is 28 because

i % a

returns the reminder of

i / a

(i divided by a) and it is only 0 when i is equal to a, i.e., 28.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.