# How to reverse a number in C

Program: Write a C program to reverse the digits of a number

Important topics:

• Remainder, division, number system, while loop.

Algorithm:

Extract all the digits from the given number and then add them by keeping the reversed place values in mind. For example, to reverse 1934, you’ll have to assign 1 in ones place(multiply by 1) and 4 in thousands(multiply by 1000) place.

### Program 1: C program to reverse a number in C using while loop

This C program uses while loop to find the reverse of a number entered by the user.

```#include<stdio.h>
int main()
{
int a,rem,rev = 0;
printf("Enter a number: ");
scanf("%d",&a);
while(a!=0)
{
rem = a%10;
a /= 10;
rev = rev*10 + rem;
}
printf("\nReversed number= %d\n",rev);
return 0;
}```

Output:

``````Enter a number: 843925

Reversed number= 529348``````

### Program 2: C program to reverse a number using function

This C program uses the same concept to reverse a number but does that using a function. You need to know the syntax of functions in C in order to understand the program.

```#include<stdio.h>
int reverse(int);      // function prototype
int main()
{
int a;
printf("Enter a number: ");
scanf("%d",&a);
printf("\nReversed number= %d\n",reverse(a));
return 0;
}
int reverse(int num)    // function definition
{
int rem,rev = 0;
while(num!=0)
{
rem = num%10;
num /= 10;
rev = rev*10 + rem;
}
return rev;
}```

Output:

``````Enter a number: 563824

Reversed number= 428365``````

### Program 3: C program to reverse a four digit number without using loop

```#include<stdio.h>
int main()
{
int a,b,c,d,rev;
printf("Enter a four digit number: ");
scanf("%d",&a);
b=a%10;
a/=10;
c=a%10;
a/=10;
d=a%10;
a/=10;
rev=b*1000+c*100+d*10+a;     //finding reverse
printf("\nReversed number= %d\n",rev);
return 0;
}```

Explanation:

a is the number entered by the user, b, c and d are used to store the digits of the number which are calculated from the remainder on dividing the number by 10. At the end, the number are given their place value in reverse order and then added to find the reverse number.

Output:

``````Enter a four digit number: 9285

Reversed number= 5829``````

In this article, we learned how to reverse a number in C with and without function. Also we used the concept to reverse a four digit number without using loop.

Share your code in the comment section to help others.

You can learn from this YouTube video: