Question
Reverse a Number using do while in C language
Solution
✔ Verified
This C program reverses the digits of a given number using a do-while loop. The process involves repeatedly extracting the last digit of the number and constructing the reversed number by appending this digit to a new number.
How it works:
- The program takes an integer input from the user.
- A do-while loop is used to reverse the number:
- In each iteration, the last digit of the number is extracted using the modulus operator (number % 10).
- This digit is added to the reversed number by multiplying the current reversed number by 10 (shifting its digits to the left) and then adding the extracted digit.
- The number is then divided by 10 (removing the last digit) using integer division (number / 10).
- The loop continues until the number becomes zero.
- After the loop finishes, the reversed number is printed.
#include <stdio.h>
int main() {
int num, rev = 0;
printf("Enter a number: ");
scanf("%d", &num);
do {
rev = rev * 10 + num % 10;
num = num / 10;
} while (num != 0);
printf("Reversed number = %d\n", rev);
return 0;
}
Output -
Enter a number: 123
Reversed number = 321Click here to download practice questions on
do while in C