Not sure whether I can explain. My thoughts went in a different direction. The function looked a bit elaborate to me, I wondered whether it could be simplified.
Original function:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
void findBinary(int num)
{
int rem;
if (num <= 1)
{
cout << num;
return;
}
rem = num % 2;
findBinary(num / 2);
cout << rem;
}
|
The variable
rem
stood out. Its use is scattered throughout the function; declared at line 3, a value is assigned at line 10 and then that value is output at line 12. Let's see if we can combine all those three uses into a single line.
1 2 3 4 5 6 7 8 9 10 11
|
void findBinary(int num)
{
if (num <= 1)
{
cout << num;
return;
}
findBinary(num / 2);
cout << num % 2;
}
|
But then, having two separate
cout
statements bothered me. Is there a way that they might be combined? Well, that seems unlikely. But, what if we temporarily increase the complexity by changing line 5 to look like line 10. The result is the same.
1 2 3 4 5 6 7 8 9 10 11
|
void findBinary(int num)
{
if (num <= 1)
{
cout << num % 2;
return;
}
findBinary(num / 2);
cout << num % 2;
}
|
Now it is seen that the only difference between the two outputs is that in one case there is a recursive function call. By changing the if statement, instead of
if (num <= 1)
consider the complementary condition,
if (num > 1)
.
This looks more complicated, but bear with me a moment.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
void findBinary(int num)
{
if (num <= 1)
{
cout << num % 2;
return;
}
if (num > 1)
{
findBinary(num / 2);
cout << num % 2;
}
}
|
Now, since both if statements contain the same cout statement, it can be moved outside of them both like this:
1 2 3 4 5 6 7
|
void findBinary(int num)
{
if (num > 1)
findBinary(num / 2);
cout << num % 2;
}
|
Now it's clearer. If the cout statement is moved to the top, the output is changed, the order of digits is reversed.
I don't know whether this helps, I didn't directly address the original question.