3

I need to determine whether an entered number has digits in ascending order from right to left.

My code seems not working correctly

Here is my code:

int n, temp; cout << "Please enter number: "; cin >> n; bool ascending = true; temp = n%10; while (n>0) { n /= 10; if (temp < n % 10) { ascending = false; } } if (ascending) { cout << "Number is ascending"; } else { cout << "Number is not ascending"; } 
1
  • In situations like this, it is best to use a debugger. Debuggers can be intimidating for beginners, so the quick alternative is to stick in a few couts to keep updated on the values of variables and where the control flow is going. Commented Jan 14, 2017 at 12:03

2 Answers 2

1

You're not updating the value of temp after every iteration

int n, temp; cout << "Please enter number: "; cin >> n; bool ascending = true; temp = n%10; while (n / 10 > 0) { n /= 10; if (temp > n % 10) { ascending = false; break; } temp = n % 10; } if (ascending) { cout << "Number is ascending"; } else { cout << "Number is not ascending"; } 
Sign up to request clarification or add additional context in comments.

6 Comments

You can also break after setting ascending = false.
@Thirupathi Thangavel oh ye right, thank you, but it still not output correct answer, for example for number "5321" - output is not ascending
@Andrew Check now
@Thirupathi Thangavel still the output is not correct
"ascending" or "ascending consecutively? the answer is correct for the former but not for the latter.
|
1

When I run the latest from Thirupathi, it does work. Note OP said ascending order RIGHT to LEFT.

Ex output runs:

./order Please enter number: 5321 Number is ascending ./order Please enter number: 2356 Number is not ascending 

1 Comment

Can you suggest a fix? Otherwise this is not an answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.