Answer to Question #328638 in C++ for Nickname

Question #328638

Write a C++ program and flowchart to swap first and last digits of a number.

1
Expert's answer
2022-04-16T15:14:42-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS