how recursion is working is not clear,how call is made on recursion for the same input and iterating over other code,when we have increased input to next input in line 22.see video
Cpp-recursion-phone keypad
Hi Shubham, with recursion we can say (broadly), it is generates the possible strings by using 1st digit and then solves it for subsequent digits. For ex:
// Input
345
Now charachters associated with:
3 - d, e, f
4 - g, h, i
5 - j , k, l
now our answer will be of 3 length let it be Q = _ _ _
Now the firstcall which goes to printkeypadstring function is:
printKeypadString( “345”, “”, 0, 0 )
in line 17 digit = 3 as “345”[0] = “3” and “3” - “0” = 3 ;
after that control passes to loop. The loop places all the chars assocated with digit=3 at 0th position of Q i.e.
at Q = _ _ _
the chars associated with 3 are d,e,f. It puts d first. Q now becomes Q = d _ _.
Then it calls
printKeypadString( “345”, “d”, 1, 1 )
It generates the value of digit which is 4. chars associated with 4 are g,h,i. It put first one i.e. g at Q[1] so Q = d g _.
Now again the printKeypadString function is called as:
printKeypadString( “345”, “dg”, 2, 2 )
It generates the value of digit which is 5, the first char associated with 5 is j, it puts j at Q[2] i.e. Q = dgj.
Now again the printKeypadString function is called as:
printKeypadString( “345”, “dgj”, 3, 3 )
Now since “345” has only 3 chars therefore it’s [3] i.e. “345”[3] = ‘\0’.
SO THE CONTROL PASSES BACK TO THE LOOP FROM WHERE IT WAS CALLED THAT IS THAT STEP WHEN Q BECAME Q = dgj
Now k is incremented and value of Q = dgj changes to dgk. Then dgl. After this when keypad[5][3] is called which is ‘\0’ so control passes to state when Q became Q = dg_.
Now k gets incremented and Q becomes Q = dh_. Same process repeats. Now
dhj
dhk
dhl
will be generated then
dij
dik
dil
…
…
…
egj
egk
egl
and same process goes on till
fil
Try putting
cout << in << ’ ’ << out << ’ ’ << i<< ’ ’ << j << endl ;
// at line 26 and then run it
Hope you understand now
Hey Shubham,
As you are not responding to this thread, I am marking your doubt as Resolved for now. Re-open it if required.
Please mark your doubts as resolved in your course’s “ Ask Doubt ” section, when your doubt is resolved.