Recursion Explanation

Can anyone help me understand this code especially in the "if (num1%num2==0)" part. I'm just wondering how come it outputs num2 even though num1%num2 is NOT equal to 0.

(Sample Output)
Type a number: 12
Output: 1 2 3 4 6 12




include <iostream>
using namespace std;
void factors(int num1,int num2){
if(num2==0){
return;
}
else{
factors(num1,num2-1);

if (num1%num2==0){
cout << num2 << " ";
}
}
}

int main(){
int num;

cout << "Type a number: ";
cin >> num;

factors(num,num);

return 0;
}
Last edited on
It outputs the divider of 12. The result of the modulo operator % is indeed 0 for this numbers.

See Arithmetic operators:

http://www.cplusplus.com/doc/tutorial/operators/
Topic archived. No new replies allowed.