Cover Image for Reverse Number in C
134 views

Reverse Number in C

To reverse a number in C, you can repeatedly extract and print the last digit of the number by taking its remainder when divided by 10. After printing the last digit, you can remove it from the number by dividing it by 10. Repeat this process until the number becomes zero. Here’s a C program to reverse a number:

C
#include <stdio.h>

int main() {
    int num, reversedNum = 0;

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

    // Reverse the number
    while (num != 0) {
        int digit = num % 10; // Extract the last digit
        reversedNum = reversedNum * 10 + digit; // Append the digit to the reversed number
        num /= 10; // Remove the last digit
    }

    printf("Reversed number: %d\n", reversedNum);

    return 0;
}

In this program:

  1. We input an integer from the user.
  2. We initialize reversedNum to 0, which will store the reversed number.
  3. Inside a while loop, we repeatedly extract the last digit of num using the modulo operator (%). This digit is stored in the digit variable.
  4. We append the digit to reversedNum by multiplying reversedNum by 10 and adding the digit to it. This effectively adds the digit to the reversed number.
  5. We remove the last digit from num by dividing it by 10.
  6. We repeat this process until num becomes zero.
  7. Finally, we print the reversedNum, which contains the reversed digits of the input number.

Compile and run the program, and it will reverse the entered integer and display the reversed number.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS