C program question: If i have a program that asks the user for a positive integer an i save that in the variable n. And then i have a while statement like so : while (n) { invert (P) n = n & n-1 } what is that while loop saying? Is it saying "while true"? isn't it always true?
C defines false as 0. C defines true as not false. Any non-zero, non-null value is true.
So if i had the fallowing code, since n does not equal zero it will always be true so then it would always loop to the while after n = n & (n-1)? int main () { int n, p; p=0; printf("Enter a positive integer:"); scanf("%d",&n); while (n) { invert(p); n = n & (n-1); } printf("Odd parity is %d\n", p); invert(p); printf("Even parity is %d\n", p); return 0; }
If n is positive, then the loop will execute at least 1 time. Note the n = n & (n-1) which will mostlikely decrease the value of n, if not set it to 0. So The while(n) look will execute 1 or more times in this cases. If n is negative on the other hand, the loop might keep on going for a while, I think it will actually be infinite if n is < 0. So it would be wise to check for n to be > 0 before going into the while loop.
What does n = n & (n-1) do?
n = n & (n-1) ; lets say that n =3 then n = 3 &2 ?? converting 3 and 2 to binary notation (11) & 10 = 10 = 2 so no the loop will eventually terminate when n&(n-1) is zero
A single ampersand is a bitwise and. A double ampersand is used in complex (more than one) conditionals to require that the conditionals on each side of it are both true: if( ( 2 == 2 ) && ( 3 == 3 ) ) puts( "Yes" ); will print.
More precisely && is a logic AND operation, while & is a bitwise AND operation. So && will return true when both operand are logically TRUE.
Join our real-time social learning platform and learn together with your friends!