Home > Blockchain >  inverse number using function - how to solve this output problem?
inverse number using function - how to solve this output problem?

Time:04-01

As a new learner of C, I managed to go this far in this little exercice, the code works (kind of). It doesn't work for the second time, the output just adds up.

int i = 0;

void inverse(unsigned int n) {
    int reste;
    if (n != 0) {
        reste = n % 10;
        i = (i * 10)   reste;
        inverse(n / 10);
    } else {
        printf("%d \n", i);
    }
}

void main() {
    inverse(1589);
    inverse(42);    
} 

Output:

9851
985124

CodePudding user response:

Your approach fails because i is not cleared before each new case. You could clear i after the printf, but a better approach is to avoid global variables. You can modify inverse for this purpose by removing the recursion:

#include <stdio.h>

void inverse(unsigned int n) {
    unsigned int i = 0;
    while (n != 0) {
        unsigned int reste = n % 10;
        i = i * 10   reste;
        n = n / 10;
    }
    printf("%u\n", i);
}

int main() {
    inverse(1589);
    inverse(42);
    return 0;    
}

Note these remarks:

  • you must include <stdio.h> to use printf()
  • main return type is int.
  • for consistency, i should have type unsigned int.

Some numbers will produce incorrect output as their inverse exceeds the range of unsigned int eg: 1000000009. You can remove this shortcoming by printing the digits instead of combining them as a number:

void inverse(unsigned int n) {
    while (n > 9) {
        putchar('0'   n % 10); 
        n = n / 10;
    }
    putchar('0'   n); 
    putchar('\n');
}

CodePudding user response:

You need to reset i at some point. The most straight forward and horrible way is to simply do it after the printf().

But you should better redesign the recursion to work without global variables. Which is not easily done with any similarity to the shown code.
This is (I realised a little late) more or less what luk2302 recommended in a comment on a deleted answer.

#include <stdio.h>

int i = 0;
void inverse(unsigned int n){
    
    int reste;
    if (n != 0) {
        reste = n % 10;
        i = (i * 10)   reste;
        inverse(n / 10);
    }
    else {
        printf("%d \n", i);
        i=0;
    }
}

void inverse2(int number, int reversed)
{
    if (number < 1)
    {
        printf("%d \n",reversed);
    } else
    {
        inverse2(number/10, reversed*10 number);
    }
    
}

void main(){

    inverse(1589);
    inverse(42);    
    inverse(123);    
    inverse2(1589,0);
    inverse2(42,0);    
    inverse2(123,0);    

} 

Output:

9851 
24 
321 
9851 
24 
321
  •  Tags:  
  • c
  • Related