C++ Program to Swap First and Last Digit in a Number

Write a C++ Program to Swap First and Last Digit in a Number with an example. This C++ program allows the user to enter any numeric value, and it finds the first and last digit, and swap them.

#include<iostream>
#include<cmath>
using namespace std;

int main()
{
	int number, firstDigit, lastDigit, count, a, b, SwapNum;
	
	cout << "\nPlease Enter Any Number to find First and Last Digit =  ";
	cin >> number;
	
	count = log10(number);  	
  	firstDigit = number / pow(10, count);
  	
  	lastDigit = number % 10;
  	
  	a = firstDigit * (pow(10, count));
  	b = number % a;
  	number = b / 10;
  	
  	SwapNum = lastDigit * (pow(10, count)) + (number * 10 + firstDigit);
  	
	cout << "\nThe First Digit in a Given Number    = " <<firstDigit; 
	cout << "\nThe Last Digit in a Given Number     = " << lastDigit; 
	cout << "\nAfter Swapping First and Last Digit  = " << SwapNum; 	
 	return 0;
}
C++ Program to Swap First and Last Digit in a Number 1

C++ Program to Swap First and Last Digit in a Number Example 2

#include<iostream>
#include<cmath>
using namespace std;

int main()
{
	int number, firstDigit, lastDigit, count, SwapNum;
	
	cout << "\nPlease Enter Any Number to find First and Last Digit =  ";
	cin >> number;
	
	count = log10(number);  	
  	firstDigit = number / pow(10, count);
  	
  	lastDigit = number % 10;
  	
  	SwapNum = lastDigit;
  	SwapNum = SwapNum  * (round(pow(10, count)));
  	SwapNum = SwapNum + number % (int)(round(pow(10, count)));
  	SwapNum = SwapNum - lastDigit;
  	SwapNum = SwapNum + firstDigit;
  	
	cout << "\nThe First Digit in a Given Number    = " <<firstDigit; 
	cout << "\nThe Last Digit in a Given Number     = " << lastDigit; 
	cout << "\nAfter Swapping First and Last Digit  = " << SwapNum; 	
 	return 0;
}
Please Enter Any Number to find First and Last Digit =  69732

The First Digit in a Given Number    = 6
The Last Digit in a Given Number     = 2
After Swapping First and Last Digit  = 29736

About Suresh

Suresh is the founder of TutorialGateway and a freelance software developer. He specialized in Designing and Developing Windows and Web applications. The experience he gained in Programming and BI integration, and reporting tools translates into this blog. You can find him on Facebook or Twitter.