C Program to Swap First and Last Digit Of a Number

In this tutorial, i am going to show you how to swap first and last digit of a number in c programs.

All C Programs to Swap First and Last Digit Of a Number

  • Program 1 – C Program to Swap First and Last Digit Of a Number
  • Program 2 – C Program to Swap First and Last Digit Of a Number

Program 1 – C Program to Swap First and Last Digit Of a Number

/* C Program to Swap First and Last Digit Of a Number */
 
#include <stdio.h>
#include <math.h>
 
int main()
{
  	int Number, FirstDigit, DigitsCount, LastDigit, a, b, SwapNum;
 
  	printf("\n Please Enter any Number that you wish  : ");
  	scanf("%d", & Number);
  	
  	DigitsCount = log10(Number); 	
  	FirstDigit = Number / pow(10, DigitsCount);
  	
  	LastDigit = Number % 10;
  	
  	a = FirstDigit * (pow(10, DigitsCount));
  	b = Number % a;
  	Number = b / 10;
  	
  	SwapNum = LastDigit * (pow(10, DigitsCount)) + (Number * 10 + FirstDigit);
	    
	printf(" \n The Number after Swapping First Digit and Last Digit =  %d", SwapNum);
 
  	return 0;
}

The result of the above c program; as follows:

Please Enter any Number that you wish  : 456
The Number after Swapping First Digit and Last Digit =  654

Program 2 – C Program to Swap First and Last Digit Of a Number

/* C Program to Swap First and Last Digit Of a Number */
 
#include <stdio.h>
#include <math.h>
 
int main()
{
  	int Number, FirstDigit, DigitsCount, LastDigit, a, b, SwapNum;
 
  	printf("\n Please Enter any Number that you wish  : ");
  	scanf("%d", & Number);
  	
  	DigitsCount = log10(Number); 	
  	FirstDigit = Number / pow(10, DigitsCount);
  	
  	LastDigit = Number % 10;
  	
  	SwapNum = LastDigit;
  	SwapNum = SwapNum  * (round(pow(10, DigitsCount)));
  	SwapNum = SwapNum + Number % (int)(round(pow(10, DigitsCount)));
  	SwapNum = SwapNum - LastDigit;
  	SwapNum = SwapNum + FirstDigit;
	    
	printf(" \n The Number after Swapping First Digit and Last Digit =  %d", SwapNum);
 
  	return 0;
}

The result of the above c program; as follows:

Please Enter any Number that you wish  : 586
The Number after Swapping First Digit and Last Digit =  685

Be First to Comment

Leave a Reply

Your email address will not be published.