Exercise in C with loop statements: Write code to reverse numbers with do-while statement

422 Views Asked by At

I have a task (currently studying the loop statement so I'm in the beginner phase)that asks to make a program to reverse an integer number so it must have the do statement .

The output should be (example):

Enter a number: 4568
The reversal is: 8654

Please put in mind that since I'm following my book so far I've studied and know the very basics + selection and loop statements. I have very limited choices so no arrays.

The book suggests to make a do loop to divide repeatedly the number by 10 until it reaches 0 this is what I did so far (code not completed) :

int main(void)
{
  int n,x;

  printf("Enter a number: ");
  scanf("%d", &n);

  printf("The reversal is: ");

  x = n % 10;

  printf("%d",x); /*outputs the last number digit in the first place*/ 

  do{



   ....
   n  /= 10;   /* for example if I divide the number 56222  by ten the output would come out as 
               5622 562 56 5*/
   ....

  }while (n!=0);



  return 0;
}

I found a way to put the last digit in the first place as you can see but I'm struggling to figure out how to reverse the rest of the numbers after dividing the number by 10 repeadetly with this very limited choices.

What should I put in the do statement? Many thanks in advance .

1

There are 1 best solutions below

0
On BEST ANSWER

int main(void)
{
      
    int n,x;
    
    printf("Enter a number: ");
    scanf("%d", &n);
    
    printf("The reversal is: ");
    
    int rev = 0;     
    
    do{
      
        x = n % 10;
        rev = rev * 10 + x; 
        n  /= 10;
    
    }while (n!=0);
    
    printf ("%d", rev);
 
    return 0;
    
}

here you need a new integer rev whose value is 0 initially. Lets take example of 432

n = 432

when you do x = n % 10 x = 2

so when you do rev = rev * 10 + x rev is 0 and value of rev will be 2

n /= 10 make n = 43

-->so in the next iteration

n = 43 x = n % 10 results in x = 3

rev value now is 2

so rev = rev * 10 + x results in 2 * 10 + 3

so rev = 23

n /= 10 results in n = 4

-->in the last iteration n = 4 x = n % 10 results in x = 4 rev value now is 23

so rev = rev * 10 + x results in 23 * 10 + 4 so rev = 234

n /= 10 results in n = 0

so when you print rev you get the answer 234 reverse of 432