Hello, I need help with my code. Were supposed to be able to sort an array which is user input, but the first number they input is supposed to be the length of the array, and everything after that is the actual array.
Here is my code:
#include <iostream>
#include <iomanip>
usingnamespace std;
int main()
{
int size;
int list[80];
bool isSorted (constint list[], int size);
void printarray(constint list[], int size);
for(int i = 0; i<80; i++)
{
cout << "Enter a value for the length of the list, then enter list: \n";
cin >> size;
cin >> list[i];
}
}
bool isSorted (constint list[], int size)
{
for(int i=0;i<size;++i)
{
if (list[i] > list[i+1])
{
cout << "The list is not sorted";
returnfalse;
}
}
cout << "The list is sorted";
returntrue;
}
I'm stuck on how I'm supposed to use the first digit of input for the array size.
"Write the following function that returns true if the list is already sorted in increasing order:
bool isSorted(const int list[], int size)
Write a test program that prompt the user to enter a list and displays whether the list is sorted or not. Here is a sample run. Note that the first number in the input indicates the number of elements in the list. This number is not part of the list. Assume the maximum list size is 80."
example of output:
Enter list: 5 2 1 4 5 6
List is not sorted
Enter list: 5 1 2 3 4 5
The list is sorted
we haven't been taught vectors yet so I'm assuming we can't use them and no i don't know how to use dynamic memory. And i think the first digit in the input is the only limit we can put on the array.
#include <iostream>
usingnamespace std;
bool isSorted(constint*, int);
void printArray(constint*, int);
int main()
{
constint max_size = 80;
int list[max_size];
int size ;
cout << "Enter list: ";
cin >> size; // We don't want to repeatedly enter the size,
// so this shouldn't be in the body of the loop.
for (int i = 0; i < size; ++i)
cin >> list[i];
// ...
}
oohhhhhh ok I see what I did! Thank you! How would I reference the main function to the isSorted function and the printArray function? That stuff has always been a bit shady to me sorry!
#include <iostream>
usingnamespace std;
bool isSorted(constint*, int);
int main()
{
constint max_size = 80;
int list[max_size];
unsignedint size;
// Get the array size.
cout << "Enter size (max 80): ";
cin >> size;
// Get the elements.
cout << "Enter " << size << " integers\n";
for (int i = 0; i < size; ++i)
cin >> list[i];
// Check if the list is sorted.
isSorted(list, size);
cout << endl;
return 0;
}
bool isSorted (constint list[], int size)
{
for(int i=0; i < size-1; ++i)
{
if (list[i] > list[i+1])
{
cout << endl << "The list is not sorted";
returnfalse;
}
}
cout << endl << "The list is sorted";
returntrue;
}
Note: In function isSorted the loop check should be "size-1" because the last element in the array should not be compared with junk value out of bound of the array. Also when there is only one element in the list there is nothing (no other element) to compare it with.