Merry Christmas! I am attempting to check if the numbers provided by the user is in numerical order or not. The logic seems reasonable but then the program does not run properly. Any suggestions?
for(int i = 1; i < 10; i++) {
int b = i - 1;
if(input[b] <= input[i]) {
if(input[i] == input[9]) {
cout << "The numbers are arranged already!";
return 0;
} elsebreak;
}
}
Do you see problem now?
Additionally: int input[9]; contains 9 numbers with indices of 0-8. But you are trying to write 10 numbers and access index 9. Which is undefined behavior.
As you already using algorithm header, why not use it facilities:
1 2 3 4 5 6 7 8 9
int main()
{
int input[10];
for(int i = 0; i < 10; i++)
std::cin >> input[i];
std::cout << (std::is_sorted(input, input + 10)?
"The numbers are arranged already!":
"The numbers are not arranged.");
}
Sorry i did not understand your problem correctly but i can correct some of your mistakes.
1st of all :
1 2 3 4
#include <iomanip> // u dont need this
#include <cmath> // nor this
#include <algorithm> // not this
#include <ctime> // nor this
Your program is good enough without that lib as well...
also
1 2 3 4 5
if(input[i] == input[9])
{
cout << "The numbers are arranged already!";
return 0; // u dont need return 0 if u use this that if statement will jump to the end and will terminate the whole program...
}
Note:How to u mean arrange them? Like 1,2,3,4,5,6... or how do u want to arrange the entered numbers.
For me to understand your problem u need to explain a bit better so i can help u
isnt it good to define your own than using facilities of standard libraries?
It is opposite of "good". Reinventing the wheel when you have already existing solution meant you are wasting your time, and your employer money, on redundand, usually subpar, potentually bugged solution.
Only reasons to do so:
1) Existing solution has flay which prevents you from utilising it in your program and you want to fix it.
2) You want to implement it as par of exploring language. As soon as you lear all this can potentually gicve you, use already existing solutions.
All the header files you need are:
iostream
vector
algorithm
So what you have to do is:
1) Get user input
2) Make a copy of user input
3) Use a stringstream to turn the copy of user input into a string and insert every element of the string into vector foo.
4) Make this function: bool sortAscend (int i, int j) {return i < j}
5) Use std::sort like this: std::sort(foo.begin(), foo.end(), sortAscend)
6) Append each element in vector to a string.
7) Use a stringstream to convert string to int.
8) Compare user input with sorted input.
9) Print result!