by Dinesh Thakur Category: Control Structures

The program segment given below obtains a number by reversing the digits in the given number.

scanf("%d", &num);

rev_num = 0;

do {

digit = num % 10;

rev_num = rev_num * 10 + digit;

num /= 10;

} while(num > 0);

printf("reverse number= %d", rev_num);

This program segment first accepts a number num from the keyboard and initializes variable rev_ num to zero. Then it uses a do...while loop to separate the digits in num and construct number rev_num in reverse order of digits, one digit at a time. Observe carefully the statement used to obtain the reversed number:

rev_num = rev_num * 10 + digit;

In this statement, the current value of rev_num is first multiplied by I0 and the value of digit is added to it. The steps in the formation of the reverse number are illustrated below for num = 1234.

 

              C Program Reverse digits in an integer number 

The code to determine the reverse number can also be written using the while loop. The code given below avoids use of variable digit. The I/O statements are omitted to save space.

rev_num = 0;

while (num > 0) {

rev_num = rev_num * 10 + num % 10;

num /= 10;

This code can be made more concise using the for loop as shown below.

for (rev_num = 0; num > 0; num /= 10)

rev num = rev num * 10 + num % 10;



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Search Content







Popular Article