Reputation: 546
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 !
Upvotes: 1
Views: 698
Reputation: 142
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.
Upvotes: 0
Reputation: 7102
%
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".
Upvotes: 0
Reputation: 223187
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.
Upvotes: 5