
- Learn C By Examples Time
- Learn C by Examples - Home
- C Examples - Simple Programs
- C Examples - Loops/Iterations
- C Examples - Patterns
- C Examples - Arrays
- C Examples - Strings
- C Examples - Mathematics
- C Examples - Linked List
- C Programming Useful Resources
- Learn C By Examples - Quick Guide
- Learn C By Examples - Resources
- Learn C By Examples - Discussion
Reversing a Number In C
Lets first understand what we mean by reversing a number. Reversing a number like 1234 is 4321. This program should give us insight of while loop. We shall also learn how to get the last digit of a number.
To get the last digit of a number (an integer) we use modulo 10. In C, Modulo operation is uses symbol (%
). Here is how it works −
To get last 1 digit of 1234 use modulo 10, (1234 % 10 = 4)
To get last 2 digits of 1234 use modulo 100, (1234 % 100 = 34)
To get last 3 digits of 1234 use modulo 1000, (1234 % 1000 = 234)
... and so on. Lets now have a look at the algorithm to reverse a string −
START Value, Reverse, Temp Reverse ← 0 WHILE Value is greater than 0 Step 1 → Extract last digit from value Temp ← Value % 10 Step 2 → Add extracted digit to Reverse Reverse ← Reverse + Temp Step 3 → Remove last digit from value Value ← Value / 10 Step 4 → Add 0 at the end of Reverse (if not yet reversed) Reverse ← Reverse * 10 END WHILE STOP
We observe that Step 4
is a bit tricky. If the number is already reversed Step 4
will add additional zero. In implementation, we place it at the beginning of the loop −
#include <stdio.h> int main() { int value = 1234; int reverse = 0; int temp = 0; printf("Value = %d\n", value); while (value > 0) { // multiplication with 10, adds a 0 at the end to accommodate new digit reverse = reverse * 10; // Extracts last digit of value temp = value % 10; // Removes last digit from value value = value / 10; // Adds extracted digit to reverse reverse = reverse + temp; } printf("Reverse = %d\n", reverse); }
Output of the program should be −
Value = 1234 Reverse = 4321