Write a recursive function in C that converts a number into a string

Posted by user3501779 on Stack Overflow See other posts from Stack Overflow or by user3501779
Published on 2014-06-11T19:18:43Z Indexed on 2014/06/11 21:25 UTC
Read the original article Hit count: 161

Filed under:
|
|
|

I'm studying software engineering, and came across this exercise: it asks to write a recursive function in C language that receives a positive integer and an empty string, and "translates" the number into a string. Meaning that after calling the function, the string we sent would contain the number but as a string of its digits.

I wrote this function, but when I tried printing the string, it did print the number I sent, but in reverse.

This is the function:

void strnum(int n, char *str)
{
    if(n)
    {
        strnum(n/10, str+1);
        *str = n%10 + '0';
    }
}

For example, I sent the number 123 on function call, and the output was 321 instead of 123.

I also tried exchanging the two lines within the if statement, and it still does the same. I can't figure out what I did wrong. Can someone help please?

NOTE: Use of while and for loop statements is not allowed for the exercise.

© Stack Overflow or respective owner

Related posts about c

    Related posts about string