Home »
C++ Programs
C++ program to swap first and last digits of a number using class
Submitted by Shubh Pachori, on September 04, 2022
Problem statement
Given a number, we have to swap its first and last digits using the class and object approach.
Example:
Input:
Enter Number : 643745
Output:
Swapped Number : 543746
C++ code to swap first and last digits of a number using the class and object approach
#include <math.h>
#include <iostream>
using namespace std;
// create a class
class SwapNumber {
// private data member
private:
int number;
// public member functions
public:
// getNumber() function to insert
// the number
void getNumber() {
cout << "Enter Number : ";
cin >> number;
}
// swapNumber() function to swap the first and
// last digit of the inputted number
int swapNumber() {
// initializing int type variables to perform operations
int last_digit, first_digit, digits, swapped;
// finding the last digit of the number
last_digit = number % 10;
// finding total number of digits in number
digits = (int)log10(number);
// finding the first digit of the number
first_digit = (int)(number / pow(10, digits));
// copying last digit in swapped
swapped = last_digit;
// multiplying digits multiple of 10
swapped = swapped * (int)pow(10, digits);
// adding middle digits in the swapped
swapped = swapped + number % ((int)pow(10, digits));
// subtracting last digit from the swapped
swapped = swapped - last_digit;
// adding first digit in the swapped
swapped = swapped + first_digit;
// returning the swapped number
return swapped;
}
};
int main() {
// create object
SwapNumber S;
// int type variable to store
// Swapped number
int number;
// calling getNumber() function to
// insert number
S.getNumber();
// calling swapNumber() function to
// swap digits
number = S.swapNumber();
cout << "Swapped Number : " << number << endl;
return 0;
}
Output
Enter Number :1234
Swapped Number : 4231
Explanation
In the above code, we have created a class SwapNumber, one int type data member number to store the number, and public member functions getNumber() and swapNumber() to store the number and to swap last and first digits of the inputted number.
In the main() function, we are creating an object S of class SwapNumber, reading the number inputted by the user using getNumber() function, and finally calling the swapNumber() member function to swap last and the first digit of the inputted number. The swapNumber() function contains the logic to swap the last and first digits of the inputted number and printing the result.
C++ Class and Object Programs (Set 2) »