# switching value of variable?

This is a discussion on switching value of variable? within the C++ Programming forums, part of the General Programming Boards category; Code: cout << "Input numbers are: " << x << " , " << y << endl; if ( x ...

1. Code:
``` cout << "Input numbers are: " << x << " , " << y << endl;

if ( x < y)

{ // exchange values of x and y

temp=x;
x = y;
y=temp;

}
cout<<"x="<<x<<",y="<<y<<endl;

/* At this point we will always have x >= y */

remainder=(x % y);

while (remainder!=0);
{
x=y;
y=x % y;
remainder=x%y;
}

// display the result
cout << endl ;
cout << "The GCD is: " << y << endl ;```

2. That's with the changes. It terminates before GCD can be displayed.

3. Code:
```    while (remainder!=0);
{
x=y;             // x = y
y=x % y;         // y = x % y = x % x = 0
remainder=x%y;   // remainder = x % y = x % 0 = crash
}```

4. That's not how the Euclidean algorithm goes. It's more like:
Code:
```x <- y
y <- remainder
remainder <- x%y```
Note the subtle difference.

5. Take a look at your while-loop:
Code:
``` remainder=(x % y);

while (remainder!=0);{
x=y;
y=x % y;
remainder=x%y;
}```
Now take a look at what the algorithm looks like:
Code:
```while b ≠ 0
t := b
b := a mod b
a := t```
Can you see the difference?

6. Well it did crash. As in nothing happend. I see the differences there in the formula. I declared remainder as an int at the start. However I was trying to intialize it and have the value declared as x%y however I don't think that worked.

7. while (remainder!=0);
In case it is there in your real code, it shouldn't be. Don't put a semicolon at the end of a loop or if statement (unless you want it to do nothing; that is, no body).

Page 2 of 2 First 12