Introduction
Swapping the first and last digits of a number is a common task in programming, often encountered in various mathematical and algorithmic problems. In this blog, we delve into a simple yet effective program to accomplish this task using the C programming language.

Also Read, Binary to Hex Converter
Example 1
To swap the first and last digit of a number, firstly, we need to input a number from the user. We will declare a type ‘int’ variable and store the user input value for inputting a number.
Our task now is to know the count of total digits in the input number.
After learning the count of digits, we will calculate the number's first digit by dividing the input number by 10 to the power of total digits in the number minus one.
Similarly, we will find out the last digit of the input number with the help of the modulo operator. After finding out the first and last digit of the input number, we will swap them, and afterwards, we will print the result.
Let us look at the algorithm and the code for this problem to get a clear understanding of the approach.
Algorithm
Step 1 - Declare the variables Num, First_Digit, Digits_Count, Last_Digit, x, y, Swap_Num. Step 2 - Input a number and store it in Num. Step 3 - Perform log10 on Num and store it in Digits_Count. Step 4 - Set First_Digit = Num/pow(10, Digits_Count). Step 5 - Set Last_Digit = Num % 10. Step 6 - Set x = First_Digit * (pow(10, Digits_Count)). Step 7 - y = Num % x. Step 8 - Num = y / 10. Step 9 - Swap_Num = Last_Digit * (pow(10, Digits_Count)) + (Num * 10 + First_Digit). Step 10 - Print the result stored in Swap_Num. |
Also read reverse a number.
Implementation
The above code will produce the following output.
Enter the number: 12356 The Number after Swapping the First Digit and Last Digit = 62351 Program finished with exit code 0 Press ENTER to exit console. |
Let us now discuss the second example of swapping the first and last digit of a number and try it to implement on C compiler.
You can also read about dynamic array in c, and Tribonacci Series You can also read about - Strong number in c