can anyone explain to me what is happening

1
2
3
4
5
6
7
8
void convert(int num) 
{
if (num>0) {
convert(num/2);
cout<<num/2;
}
}


if i put num as 17 it will display 10001 i want to know why? i don't get the recursive function's function
It will display 01248, not 10001.
When in question, just "execute" the function yourself mentally or on paper.
Last edited on
no the asnwer is 10001
Are you sure that's what you get?

I get "01248" which are actually five seperate numbers. First "main(...)" calls "convert(...)" and passes it your number '17' in this case. '17' is greater then '0' so "convert(...)" is called again but this time it should be passed either '7' or '8', depending on if your compiler rounded up or down. Since those are both larger then '0' again they are divided again by '2' and passed to "convert(...)" again...

It goes on like that until num is '0'. Then starting with the last time that "convert(...)" was called, line 5 executes and prints what the number passed to it divided by 2 is.
no, the answer is 01248 like Athar said.

If you're not getting 01248, you're doing something you're not telling us, or using a number other than 17. Show us how you're calling this function.

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

void convert(int num) 
{
    if (num>0) {
        convert(num/2);
        cout<<num/2;
    }
}

int main()
{
    convert(17);
    cin.get();
}
01248
Last edited on
Post your entire code then. I'm willing to bet you're not passing the number right.
17/2 = 8(becuase it's in) 8/2 = 4, 4/2 = 2, 2/2 = 1
teh set of numbers are

17, 8, 4, 2, 1
1%2 = 1
8 4 and 2 % 2 = 0
17 mod 2 = 1
therefore it is

1(1%2),0(2%2),0(4%2),0(8%2),1(17%2)

oh wait the cout<<num%2;
Last edited on
You had a typo then, your origional post said divide not modulate.
Last edited on
i'm sorry.
Topic archived. No new replies allowed.