C program to reverse a given number

C Programming C Programming Code Example

C program to reverse a given number

Problem:
Write a C program to reverse a given number.

Logic for getting reverse number in C:
Suppose, we’ve given a number 123456, then we’ll get the reverse output of that number like 654321.
Logic:

Use the techniques of reminder. First take the last part of the number after dividing it by 10 and take the reminder.
Suppose,
123. after dividing it by 10 and taking reminder part, we can get 3.
Then we need only 12 as next loop value. So, divide the number by 10 and get the value, like 12.
Now first multiply 10 to the previous number that was 3 and 3 * 10 = 30.
Now we’ve 12 and taking it’s reminder part 2 and our reverse number is 32.
And….
same procedure and get the reverse number. Hope you can understand to make a number reverse in C.

Solution:
C program to reverse a given number:

#include <stdio.h>
int main()
{
int n, reverse = 0;

printf("Enter a number to reverse : n");
scanf("%d", &n);

while (n != 0)
{
reverse = reverse * 10;
reverse = reverse + n%10;
n = n/10;
}

printf("Reverse of entered number is = %dn", reverse);

return 0;
}

C program to reverse a given number: Output

C program to reverse a given number using recursion method:

#include <stdio.h>
long reverse(long);

int main()
{
long n, r;

scanf("%ld", &n);

r = reverse(n);

printf("%ldn", r);

return 0;
}

long reverse(long n) {
static long r = 0;

if (n == 0)
return 0;

r = r * 10;
r = r + n % 10;
reverse(n/10);
return r;
}

Tags:
C program to reverse a given number, Reverse a number, reverse number code in C programming, C program to reverse a given number, C programming

Leave a Reply

Your email address will not be published.