🔄

Reversing a Number in C Program

Sep 8, 2024

C Program to Print Reverse of a Given Number

Introduction

  • Objective: Print the reverse of a given number.
  • Example Outputs:
    • Input: 786 → Output: 687
    • Input: 12 → Output: 21
    • Input: 1234 → Output: 4321

Logic

  • To reverse a number, extract digits one by one from the end.
  • Use modulo operation to get the last digit and division to reduce the number.

Steps to Reverse a Number

  1. Extract Last Digit:
    • Use n % 10 to get the last digit.
  2. Build the Reversed Number:
    • rev = rev * 10 + remainder
    • Start with rev = 0.
    • Repeat until the original number is reduced to 0.
  3. Reduce the Number:
    • Use n = n / 10 to remove the last digit.
  4. Loop Until Completion:
    • Repeat steps until n becomes 0.*

Example Walkthrough

  • For the number 1234:
    1. Iteration 1:
      • n = 1234
      • Last digit = 4
      • rev = 0 * 10 + 4 = 4
      • n becomes 123
    2. Iteration 2:
      • n = 123
      • Last digit = 3
      • rev = 4 * 10 + 3 = 43
      • n becomes 12
    3. Iteration 3:
      • n = 12
      • Last digit = 2
      • rev = 43 * 10 + 2 = 432
      • n becomes 1
    4. Iteration 4:
      • n = 1
      • Last digit = 1
      • rev = 432 * 10 + 1 = 4321
      • n becomes 0
  • Output: 4321

C Program Implementation

  • Include necessary header files:
#include <stdio.h>
  • Define main function:
int main() {
  • Declare variables:
    • int n, r, rev = 0;
  • Prompt user for input:
printf("Enter a number: "); scanf("%d", &n);
  • Loop through the logic until n is not 0:
while (n != 0) { r = n % 10; rev = rev * 10 + r; n = n / 10; }
  • Print the result:
printf("Reverse of the number is: %d\n", rev);
  • Close the main function:
return 0; }

Conclusion

  • This program successfully reverses a given number using basic arithmetic operations and loops.