while(integer)

What does while(r) below mean? What is it testing?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

int sgd(int m, int n){
    int r=m%n;
    while(r){
        m=n;
        n=r;
        r=m%n;
    }
    return n;
}

int main(){
    int number1, number2, answer;
    cout << "Enter two integers: "; cin >> number1 >> number2;
    answer = sgd(number1, number2);
    cout << answer;
}
while (r) is equivalent to while (r != 0)

EDIT: Be careful, it does not mean while (r > 0). I learnt this the hard way when one of my loops ( while (r) ) got executed even for negative values of r.
Last edited on
Thanks.
Topic archived. No new replies allowed.