In C, a Reverse a Number program takes a number and reverses its digits. For example, if the input is 12345, the output will be 54321. This is typically done using a combination of mathematical operations like modulo (%) and division (/).

Logic to Reverse a Number:

  1. Extract the last digit using the modulo operator (%).
  2. Build the reverse number by appending the extracted digit.
  3. Remove the last digit from the original number using division (/).
  4. Repeat the process until all digits are reversed.

Program:

#include <stdio.h> int main() { int num, reversed = 0, remainder; // Input a number from the user printf("Enter an integer: "); scanf("%d", &num); // While loop to reverse the digits of the number while (num != 0) { remainder = num % 10; // Extract the last digit reversed = reversed * 10 + remainder; // Build the reversed number num = num / 10; // Remove the last digit from the original number } // Output the reversed number printf("Reversed number = %d\n", reversed); return 0; }

Explanation:

  1. Variables:

    • int num: This stores the original number input by the user.
    • int reversed: This stores the reversed number, initialized to 0.
    • int remainder: This stores the remainder, which is the last digit of the original number.
  2. Input:

    • scanf("%d", &num); takes the input number from the user.
  3. Reversing Logic:

    • Extract the Last Digit: remainder = num % 10; extracts the last digit of num.
    • Build the Reverse Number: reversed = reversed * 10 + remainder; appends the extracted digit to reversed. Initially, reversed is 0, so for each digit, it multiplies by 10 and adds the new digit.
    • Remove the Last Digit: num = num / 10; removes the last digit from the original number by dividing it by 10.
  4. Loop:

    • The process is repeated inside the while (num != 0) loop until the original number becomes 0, meaning all digits have been reversed.
  5. Output:

    • The program prints the reversed number using printf.

Sample Output:

Example 1:

Enter an integer: 12345 Reversed number = 54321

Example 2:

Enter an integer: 67890 Reversed number = 9876

Key Points:

  • Modulo Operation (%) is used to extract the last digit of the number.
  • Division by 10 (/) is used to remove the last digit from the number.
  • The reversed number is built by multiplying the current reversed value by 10 and adding the extracted digit.

This is a common beginner-level program in C, helping you understand loops, arithmetic operations, and basic input/output handling.