Using iterative function print the given number in reverse order in C language

CServer Side ProgrammingProgramming

Problem

How to print the given in reverse order with the help of iterative function i.e., while loop using C programming language?

Solution

So far, we had seen how to reverse the string using string function and without string function, now let’s see how to reverse a number without using predefined function −

Algorithm

Input − give a number at runtime

Step 1: Declare the variable number,reverse
Step 2: Initialize reverse= 0
Step 3: while number>0
        (a) reverse=reverse*10 + number%10;
            reverse = reverse*10 + num%10;
        (b) Divide number by 10
Step 4: return reverse

Example

 Live Demo

#include <stdio.h>
int reverse(int number){
   int reverse = 0;
   while(number > 0){
      reverse = reverse*10 + number%10;
      number = number/10;
   }
   return reverse;
}
int main(){
   int number;
   printf("enter a number:");
   scanf("%d",&number);
   printf("Reverse of no. is %d", reverse(number));
   getchar();
   return 0;
}

Output

enter a number:356789
Reverse of no. is 987653
raja
Published on 05-Mar-2021 10:23:25
Advertisements