Thursday, 9 June 2016

Reverse a number

n1 % n2 = r
Mod operator(%) gives the remainder r when n1 is divided by n2.

1234 % 10 = 4

Code

#include<stdio.h>

int main()
{
    int n,rem,rev_no = 0;

    printf("Enter an integer ");
    scanf("%d",&n);

    while(n != 0)
    {
        rem = n % 10;
        rev_no = rev_no*10 + rem;
        n = n/10;
    }
    printf("Reversed number = %d",rev_no);

    return 0;
}


O/P


Code tracing


Let n = 1234
rem = 1234 % 10 = 4
rev_no = 0*10 + 4 = 4
n = 1234/10 = 123 (n is integer)

rem = 123 % 10 = 3
rev_no = 4*10 + 3 = 43
n = 123/10 = 12

rem = 12 % 10 = 2
rev_no = 43*10 + 2 =432
n = 12/10 = 1

rem = 1 % 10 = 1
rev_no = 432*10 + 1 = 4321
n = 1/10 = 0  (STOP)

No comments:

Post a Comment