loop problem

hey every one...
i want an idea about the meaning of if(x %2)????
when i working with this problem i think that the initial value of x is 1 and the condition if(x%2) will be false because number one is not even !! isn't that??? so it will not enter the statements inside this if block, after that it will go to else block and i find a problem because the value of y is not initialized and how to find the value of total????
could anyone tell me where i made mistake?.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  int x = 1, total = 0, y ;
while (x <= 6)
{
if( x % 2)
{ y = x * x;
x++;
continue;
}
else
{ total += y;
cout << "x is " << x << endl;
}
++x;
}
cout << "Total is " << total <<endl;
then initialize the value of y to be zero
Building on what Dhruv already stated.

The modulus operator (%) returns what we would call the remainder of a division, so 1%2 returns a 1 and 2%2 returns a 0. Now, the if statement will execute if and only if its condition is true, or nonzero in your case. Therefore, your first if block will execute on the first run. Your test for an even number is actually reversed.
Topic archived. No new replies allowed.