Write a program to reverse a number in c
In this post, you will learn how to reverse a number in C programming language. These are different ways to reverse a number in C.
Reverse a number in C using while loop
In the given C program, we have used the while loop to find the reverse of the given number. This program takes user input and loop until num != 0 is false (0) -
#include <stdio.h>
int main() {
int num, rev = 0, rem;
printf("Please enter an integer : ");
scanf("%d", &num);
while (num != 0) {
rem = num % 10;
rev = rev * 10 + rem;
num /= 10;
}
printf("Reverse of entered number %d", rev);
return 0;
}
Output of the above code -
Please enter an integer: 52434
Reverse of entered number 43425
Reverse a number in C using recursion
Recursion function is a function which is call itself. In the given example, we call the recursion function to get the reverse of a number. A recursion function continues until some condition is met to prevent it. That's why, we use the if statement to break the infinite recursion. In the given C program, we have used recursion to reverse a given number -
#include <stdio.h>
long reverse(long);
int main()
{
long num, rev;
printf("Please enter an integer : ");
scanf("%ld", &num);
rev = reverse(num);
printf("Reverse of entered number : %ld\n", rev);
return 0;
}
long reverse(long num) {
static long rev = 0;
if(num == 0)
return 0;
rev = rev * 10;
rev = rev + num % 10;
reverse(num/10);
return rev;
}
Output of the above code -
Please enter an integer : 423222
Reverse of entered number : 222324
Reverse a number in C using for loop
In the given example, we have used the for loop to find the reverse of the given number.
// Reverse a number in C using for loop
#include<stdio.h>
void main(){
int num, rev_num=0, remainder, x;
printf("Enter the number to reverse: ");
scanf("%d",&num);
x = num;
for(;num>0;){
remainder = num%10;
rev_num = rev_num*10+remainder;
num = num/10;
}
printf("Reverse of %d is %d",x,rev_num);
}
Output of the above code:
Enter the number to reverse: 876234
Reverse of 876234 is 432678
Related Articles
Prime factors of a number in cArmstrong number program in c
Write a program to check leap year in c
C program to find area of rectangle
C program to convert celsius to fahrenheit
Fibonacci series program in C using recursion
Write a program to find area of circle in C
C program to find greatest of three numbers
C program for addition of two numbers
C program to calculate compound interest
C program to find the ASCII value of a character
C program to convert Decimal to Octal
C program to convert decimal to binary
Write a C program to calculate Simple Interest
C program to check whether a number is even or odd
C program to check palindrome number
C program to check whether an alphabet is a vowel or consonant
Program to find square root of a number in C
C program to check whether a number is positive or negative