C Program to Reverse a Number

CodingTute

C Programming Examples

In this tutorial, you will learn how to reverse a number using c programming.

C Program to Reverse a Integer

#include <stdio.h>

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

  // Read the number from the user
  printf("Enter a number: ");
  scanf("%d", &num);

  // Reverse the number
  while (num > 0) {
    rev = rev * 10 + num % 10;
    num /= 10;
  }

  // Print the reversed number
  printf("Reversed number: %d\n", rev);

  return 0;
}

Output

Enter a number: 1234
Reversed number: 4321

Explanation

  • The program first reads the number from the user using scanf().
  • It then initializes a variable rev to 0 and enters a loop. The loop continues as long as num is greater than 0.
  • Inside the loop, rev is updated to rev * 10 + num % 10. This effectively appends the last digit of num to rev. For example, if num is 123 and rev is 0, then after the first iteration, rev will be 3, after the second iteration it will be 30, and after the third iteration it will be 300.
  • num is then updated to num / 10, which removes the last digit. For example, if num is 123, it will become 12 after the first iteration, 1 after the second iteration, and 0 after the third iteration, at which point the loop will terminate.
  • Finally, the reversed number is printed using printf().

You can find more C Programming Examples here.

Follow us on Facebook, YouTube, Instagram, and Twitter for more exciting content and the latest updates.

Exit mobile version