Reverse a number
In this article, we will look at a C program that checks if a number is palindrome or not with example and explanation.
The number to be tested will be taken as input from the user.
To reverse a number, we need to loop over the digits of the number.
In every iteration, we need to extract its rightmost digit, multiply it by 10 and add then next rightmost digit to it.
So, below are the steps that need to be performed to reverse a number.
1. Initialize a variable to hold the reversed number with 0. 2. Divide the original number by 10 to get the remainder. 3. Multiply the variable defined in Step 1 by 10 and add remainder obtained in Step 2. Assign the result to the variable defined in Step 1. 4. Remove the rightmost digit from the number by dividing it by 10. 5. Repeat steps 2 to 4 till the original number becomes 0.
To get the remainder of division in C, use modulus operator(%
) and to divide a number to get quotient, use division operator(/
).
C program
C program written as per above algorithm is given below.
#include<stdio.h> void main() { // declare variables int num, reversedNumber = 0, remainder; printf("Enter a number: "); // read value scanf("%d", &num); // loop till all digits are removed while( num != 0 ) { // get remainder of division by 10 remainder = num % 10; reversedNumber = reversedNumber * 10 + remainder; // get quotient of division num /= 10; } printf("Reversed number is %d\n", reversedNumber); }
Output is
Enter a number: 456
Reversed number is 654
Note that /= is a shorthand operator for division and assignment. So, the statement num /= 10
is equivalent to num = num/10
.