This C program reverse a given number. To reverse a given number, last digit of the number is obtained using the modulus operator (remainder left after division by 10). After this the last digit is cut off using the integer division of the number by 10. This cycle continues until the number becomes 0.
C program to reverse a number - Source code
/* C program to reverse a given number */
long num, reverse = 0, temp, remainder;
printf("Enter the number\n");
temp = num;
while (num > 0)
remainder = num % 10;
reverse = reverse * 10 + remainder;
num /= 10;
printf("Given number = %ld\n", temp);
printf("Its reverse is = %ld\n", reverse);
Enter the number
Given number = 12345
Its reverse is = 54321
1. Take the number which you have to reverse as the input and store it in the variable num.
2. Copy the input number to the another variable temp. This is done to preserve the original number for printing in the end.
3. Firstly initialize the variable reverse to zero.
4. Obtain the remainder of the input number using the modulus operator (num%10).
5. Multiply the variable reverse with 10 and add the Obtained remainder to it and store the result in the same variable.
6. Obtain the quotient of the input number (integer division by 10) and considering this as input number repeat the steps as mentioned above until the obtained quotient becomes zero.
7. When it becomes zero, print the given number and its reverse using variables temp and reverse respectively as output.
Install Computer Science Bits Android app to access all study material on the go.