 if value of a=55 , b=10
then predict output of that code and why
while(b)
b ^= a ^= b ^= a %= b;

m getting confused what it means
b ^= a ^= b ^= a %= b;

predict value of a

1 Like

Here, % is the modulo operator (x%y returns the remainder when x is divided by y)

^ is bitwise XOR operator (x^y implies convert x and y to binary form apply xor ie 1^1=0, 0^0=0, 1^0=1, 0^1=1)

Statements with multiple = operator are evaluted from right to left. So b ^= a ^= b ^= a %= b is equivalent to:

a%=b; b^=a; a^=b; b^=a; or equivalently

a=a%b; b=b^a; a=a^b; b=b^a;

To simplify things, the statements (b^=a; a^=b; b^=a;) are used to swap the values of a and b . You can check this by taking any 2 numbers.

Now the code is reduced to:

while(b)

{ a=a%b;

swap(a,b);

}

Initially, a=55,b=10;

On 1st iteration, a=55%10=5 then swap(a,b) gives a=10, b=5;

On 2nd iteration, a=10%5=0 then swap(a,b) gives a=5, b=0

As b=0, the while loop terminates and the final values are a=5 and b=0.

1 Like

And at the end, variable ‘a’ has the value of gcd(a,b).

1 Like

I hate such questions, it’s not used in real programming anyway…

2 Likes