Printing the numbers in reverse order using Division and modulo operators using C


Problem

How to print the given two-digit number in reverse order with the help of division and Modulo operator 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 the two-digit number without using the predefined function.

The logic we use to reverse the number with the help of operators is −

int firstno=number%10; //stores remainder
int secondno=number/10;// stores quotient

Then print the first number followed by the second number then you will get the reverse number for the given number.

Program 1

In this example, we will take a 2-digit number and apply division and modulo operator to reverse the number −

#include<stdio.h>
int main(){
   int number;
   printf("enter a number:");
   scanf("%4d",&number);
   int firstno=number%10; //stores remainder
   int secondno=number/10;// stores quotient
   printf("After reversing =%d%d
",firstno,secondno);    return 0; }

Output

enter a number:45
After reversing =54

Program 2

In this example, we will take a 3-digit number and apply division and modulo operator to reverse the number −

 Live Demo

#include<stdio.h>
int main(){
   int number,num1,num2,num3,result;
   printf("enter a number:");
   scanf("%4d",&number);
   num1 = number / 100;
   num2 = (number % 100) / 10;
   num3 = number%10 ;
   result = 100*num3 + 10*num2 + num1;
   printf("After reversing =%d
",result);    return 0; }

Output

enter a number:479
After reversing =974

Updated on: 05-Mar-2021

964 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements