Explanation of Code Challenge #1

Let’s take a 3 digit no. 158

To reverse this digit we need to replace ones digit(8) with hundreds digit (1).

We need to divide the integer(158) with 10 to get remainder 8. In computer programming we use %(modulus) operator to calculate the remainder.

One’s digit(8) will be obtained by expression 158%10.

Now we need hundred’s digit so for it we will divide 158 by 100. Therefore the expression will be 158/100 and it will give 1.

Note: When we didvide an integer by another integer in a programming language like C/C++. It will give only integer value i.e, 158/100 will give 1  (not 1.58) as fractional part is removed.

Now we would also need tens’s place. for it we will divide 158 by 100, take remainder and subtract ones place from it. i.e,

158%100-158%10

Now we have obtained 50 as it is. We don’t need to change its’s value as it’s place is not being changed.

The reverse digit will be:

(158%10)*100+(158%100-158%10)+158/1 [which will give (8*100+50+1)=51]

Now if we have any 3 digit integer in variable ‘a’ we can get its reversal by
above expression which can be re written as:

x=(a%10)*100+a%100-a%10+a/100

Solving Mathematically(manually), we get:

x=(a%10)*99+a%100+a/100



A valid C program for reversing a 3 digit integer can be written as

/* A program for reversal of any 3 digit positive integer*/


#include

void main()

{

int a,x;

clrscr(); ///TO clear screan

printf(”Enter 3 digit integer to reverse its value: ”);

scanf(”%d”,&a);

x=(a%10)*99+a%100+a/100;

printf(”\nThe reversed digit is: %d”,x);

getch();
}



Please consider sharing this page so we can reach more people this way.


Your suggestions are always welcome.







Comments