In this blog post, we learn how to write a C Program to swap first and last digit of a number?. We will write the C Program to swap first and last digit of a number using the mathematical operation. Here we will see the logic to swap first and last digit of a number in C program. Let see an example,
Input : 12345 || \/ Output : 52341
Algorithm to swap first and last digit of a number:
1. Ask the user to enter an integer number. Suppose n = 12345, where n is an integer variable.
int n = 12345;
2. To find the last digit of a number, we use modulo operator %. When modulo divided by 10 returns last digit of the input number.
lastDigit = num % 10
3. Find the first digit with the help of mathematical operation.
//Find total number of digit - 1 digit = (int)log10(n); //Find first digit firstDigit = (int) (n / pow(10, digit));
4. Use below logic to swap first and the last digit.
swappedNum = lastDigit; swappedNum *= (int) round(pow(10, digits)); swappedNum += n % ((int)round(pow(10, digits))); swappedNum -= lastDigit; swappedNum += firstDigit;
C Program to swap first and last digit of a number:
In the below program I am using three mathematical function pow(), log10(), and round(). I want to give a small introduction about these mathematical functions it helps to understand the code.
- pow() is used to find the power of a number.
- log10() is used to find a log base 10 value of the passed parameter.
- round() is used to round a number to the nearest integer.
#include <stdio.h> #include <math.h> int main() { int n,firstDigit, lastDigit,digits, swappedNum; printf("Enter number = "); scanf("%d", &n); //Find last digit of a number lastDigit = n % 10; //Find total number of digits - 1 digits = (int)log10(n); //Find first digit firstDigit = (int) (n / pow(10, digits)); swappedNum = lastDigit; swappedNum *= (int) round(pow(10, digits)); swappedNum += n % ((int)round(pow(10, digits))); swappedNum -= lastDigit; swappedNum += firstDigit; printf("Number after swapping first and last digit: %d", swappedNum); return 0; }
Output:
Enter number = 12345
Number after swapping first and last digit: 52341
Code Explanation:
From the above Program to Swap First and Last Digit Of a Number example, you can see that the user entered value = 12345
lastDigit = 12345 % 10 => 5
digits = log10(12345) => 4
firstDigit = 12345 / pow (10, 4) => 12345 / 10000 => 1
swappedNum = LastDigit = 5;
swappedNum = swappedNum * (round(pow(10, digits)));
swappedNum = 5 * round(pow(10, 4)) => 5 * 10000 => 50000;
swappedNum = swappedNum + Number % (round(pow(10, digits)))
swappedNum = 50000 + (12345 % 10000) => 50000 + 2345 => 52345
swappedNum = swappedNum – LastDigit
swappedNum = 52345 – 5 => 52340
swappedNum = swappedNum + FirstDigit
swappedNum = 52340 + 1 => 52341