168k views
7 votes
Write a C++ program to read from the user an integer number of 4 digits and display it in reverse order. For example, if the input is 5723 the output should be 3275. (Hint use / and %). The program should display “Invalid input” if the input value is not a 4 digits number.

2 Answers

13 votes

Answer:

#include <iostream>

using namespace std;

int main() {

int n, reversedNumber = 0, remainder;

cout << "Enter a number: ";

cin >> n;

int length = to_string(n).length();

if (length == 4){

while(n != 0) {

remainder = n%10;

reversedNumber = reversedNumber*10 + remainder;

n /= 10;

}

cout << "Reversed Number = " << reversedNumber << endl;

}

else{

cout << "Invalid Input!" << endl;

}

return 0;

}

Step-by-step explanation:

So, it's pretty easy. It finds the remainder to reverse the number and for the invalid input part, you convert the input...

Step-by-step explanation:

User Bkdir
by
3.0k points
6 votes

Answer:

#include <iostream>

using namespace std;

int main() {

int n, reversedNumber = 0, remainder;

cout << "Enter a number: ";

cin >> n;

int length = to_string(n).length();

if (length == 4){

while(n != 0) {

remainder = n%10;

reversedNumber = reversedNumber*10 + remainder;

n /= 10;

}

cout << "Reversed Number = " << reversedNumber << endl;

}

else{

cout << "Invalid Input!" << endl;

}

return 0;

}

Step-by-step explanation:

So, it's pretty easy. It finds the remainder to reverse the number and for the invalid input part, you convert the input into a string and then use .length() to find the length. Then you can reverse the number and show whatever output

User Chihiro
by
3.3k points