C Programming Code Examples C > For Loops and While Loops Code Examples C program to swap first and last digit of a number C program to swap first and last digit of a number Write a C program to input a number from user and swap first and last digit of the given number. How to swap first and last digits of a number in C programming. Logic to swap first and last digit of a number in C program. Logic to swap first and last digit of a number Begin: read(number) lastDigit = number % 10; digits = log10(number); firstDigit = number / pow(10, digits); swappednumber = lastDigit * pow(10, digits); swappednumber = swappednumber + number % pow(10, digits); swappednumber = swappednumber - lastDigit; swappednumber = swappednumber + firstDigit; End Let us do a dry run of the algorithm to get grip on the logic. Suppose number = 12345 -------------------- lastDigit = 12345 % 10 => 5 digits = log10(12345) => 4 firstDigit = 12345 / pow (10, 4) => 12345 / 10000 => 1 swappednumber = 5 * pow(10, 4) => 5 * 10000 => 50000 swappednumber = 50000 + (12345 % 10000) => 50000 + 2345 => 52345 swappednumber = 52345 - 5 => 52340 swappednumber = 52340 + 1 => 52341 /* C program to swap first and last digit of a number */ #include <stdio.h> #include <math.h> int main() { int number, swappednumber; int firstDigit, lastDigit, digits; /* Input number from user */ printf("Enter any number: "); scanf("%d", &number); /* Find last digit */ lastDigit = number % 10; /* Find total number of digit - 1 */ digits = (int)log10(number); /* Find first digit */ firstDigit = (int)(number / pow(10, digits)); swappednumber = lastDigit; swappednumber *= (int) pow(10, digits); swappednumber += number % ((int) pow(10, digits)); swappednumber -= lastDigit; swappednumber += firstDigit; printf("Original number = %d", number); printf("Number after swapping first and last digit: %d", swappednumber); return 0; }