+ 8

[SOLVED] What will be the output of this code segment?

precondition: x>=0; void demo(int x) { cout<<x%10; if(x/10!=10) { demo(x/10); } cout<<x%10; } input x=1234 Please explain how does this recursive function work? Please explain step by step. Thanks.

15th Dec 2017, 8:43 AM
***
6 Respuestas
+ 12
input x = 1234 cout<<x%10 =4 if(4!=0) true so demo x/10=123 now again x%10=123%10=3 =3 if cond. true so demo x/10=12 again x%10=2 =2 if **** true so **** x/10=1 again x%10=1 =1 x/10=1/10=0 if cond false so loop terminates.... output=4321 I hope this helps😊😊😊 it just inverse the input well u have specified wrong cond. of if it should be if(x/10!=0) if it is true then pre cond. should be x>0... otherwise it will loop infinitely.
15th Dec 2017, 9:04 AM
🌛DT🌜
🌛DT🌜 - avatar
+ 1
i think it will be infinite recursion.
15th Dec 2017, 10:06 AM
Greeshma.B.K
Greeshma.B.K - avatar
0
The program enters the user during the morning and evening and the night and the program printing period in the hours of morning can you help me The fastest speed
15th Dec 2017, 9:15 AM
Bakre Mohmed Ali
Bakre Mohmed Ali - avatar
0
plaese
15th Dec 2017, 9:15 AM
Bakre Mohmed Ali
Bakre Mohmed Ali - avatar
- 1
Agree with everybody but Deoanshu is the most accurate. Initially x0 =1234 and demo only runs if x >=0 Original call demo(x0) Output 4 If0 x0/10 =123=x1!=10 then demo(x1) Output 4 Sub run on x1 demo(x1) x1>=0 Output 3 If0 x1/10 =12=x2!=10 then demo(x2) Output 3 Sub run on x2 demo(x2) x2>=0 Output 2 If0 x2/10 =1=x3!=10 then demo(x3) Output 2 Sub run on x3 demo(x3) x3>=0 Output 1 If0 x3/10 =0=x4!=10 then demo(x4) Output 1 ***infinite loop error Sub run on x4 demo(x4) x4>=0 Output 0 If0 x4/10 =0=x5!=10 then demo(x5) Output 0 So the output would be 43210000....infinity crash out of memory If x>0 it depends where in demo function. If around entire body then output should 43211234 If before recursive demo call 4321001234
15th Dec 2017, 4:42 PM
H Chiang