In this tutorial, we will write a C program to reverse a number using loops. Before that, you may go through the following topics in C.
To reverse an integer in C is achieved using loop and operators. For example, if the input number is 123 then the program should give 321 as a result.
We will learn three ways to display the number in reverse order in C.
All of the programs below take the user input for an integer. Then using three different loops in C, we calculate the reverse of the number entered. The final result is displayed at the end.
C program to reverse a number using while loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #include <stdio.h> int main() { int num, rev = 0, rem; //User Input printf("Enter the Number: "); scanf("%d", &num); while (num != 0) { rem = num % 10; rev = rev * 10 + rem; num /= 10; } printf("Reversed number: %d", rev); return 0; } |
Output:
Enter the Number: 1234
Reversed number: 4321
C program to reverse a number using for loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include <stdio.h> int main() { int num, rev = 0, rem; //User Input printf("Enter the Number: "); scanf("%d", &num); for (; num != 0; num = num / 10) { rem = num % 10; rev = rev *10 + rem; } printf("Reversed number: %d", rev); return 0; } |
Output:
Enter the Number: 1234
Reversed number: 4321
C program to reverse a number using do-while loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include <stdio.h> int main() { int num, rev = 0, rem; //User Input printf("Enter the Number: "); scanf("%d", &num); do { rem = num % 10; rev = rev *10 + rem; num /= 10; } while (num != 0); //condition printf("Reversed number: %d", rev); return 0; } |
Output:
Enter the Number: 1234
Reversed number: 4321
C program to reverse a number using recursion
Learn more on recursion function in C programming
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | #include <stdio.h> int reverse(int); int main() { int num, result; printf("Enter the Number: "); scanf("%d", &num); result = reverse(num); printf("Reversed number: %d", result); return 0; } int reverse(int n) { static int rev = 0; if (n == 0) return 0; rev = rev * 10; rev = rev + n % 10; reverse(n / 10); //recursion return rev; } |
Output:
Enter the Number: 1234
Reversed number: 4321