Write a C++ program and flowchart to swap first and last digits of a number.
#include <iostream>
using namespace std;
int swap_first_last(int x) {
int first, last, power10;
if (x < 10)
return x;
last = x % 10;
power10 = 1;
do {
power10 *= 10;
first = x / power10;
} while (first > 9);
int middle = ((x/10) % (power10/10));
return last * power10 + middle * 10 + first;
}
int main() {
int x;
cout << "Enter a positive number: ";
cin >> x;
cout << "Swap first and last digits: " << swap_first_last(x) << endl;
return 0;
}
Comments
Leave a comment