548 views
5 votes
5 votes

How will this function run for the input 123 (where str points '123' and n=3)?

in myAtoiRec(int *str,int n)
{
    if(n==1)
    return*str-'0';
    return(10*myAtoiRec(str,n-1)+str[n-1]-'0');
}

 

1 Answer

Best answer
1 votes
1 votes

we know that, we have characters in the string, for this function, we have '0','1',....'9' only therefore following basic point is always true.

Basic Point :- subtracting '0' from the character ===> making character into integer.

 

in myAtoiRec(int *str,int n)
{
    if(n==1)
       return*str-'0';
    return(10*myAtoiRec(str,n-1)+str[n-1]-'0');
}

in this function, 

recursion is myAtoiRec(str,n-1) ====> Length Reducing ==> Str is a pointer therefore cut the last character from the string

WHY the last character in the string cut? why NOT first character in the string?

because on the first recursion str[n-1] means str[n-1-1] = str[n-2] in the original calling function, from these we can conclude that last character is cut from the string in every recursion.

str[n-1] ====> Last character pointed by the str pointer

str[n-1]-'0' ====> Convert Last character pointed by the str pointer into the INTEGER

 

let a integer is ABCD where A, B, C and D represents digits

∴ ABCD = 103.A+102.B+101.C+D

Assume we supply "ABCD" string pointer as the i/p for the function.

Our function returns

= 10 * ( "ABC") + D

= 10 * ( 10 * "AB" + C ) + D = 102 . ( " AB" ) + 101 C + D

= 102 . ( 10 * "A" + B ) + 101 C + D = 103 . ( "A" )  + 102 . B  + 101 C + D

= 103 . ( A )  + 102 . B  + 101 C + D

= 103 .A  + 102 . B  + 101 C + D

Hence we can conclude that, Given function is implementation of atoi()

selected by

Related questions

1 votes
1 votes
3 answers
1
jverma asked May 23, 2022
1,027 views
#include <stdio.h>int f(int n){ static int r = 0; if (n <= 0) return 1; r=n; return f(n-1) + r;}int main() { printf("output is %d", f(5)); return 0;}Ou...
1 votes
1 votes
0 answers
4
KISHALAY DAS asked Dec 21, 2016
287 views