Reputation: 1
Here is the assignment:
Your goal is to write a program that displays a series of whole numbers from input in reverse order. Your program will prompt the user for the number of values in this list, which it will use as the size for a dynamic array declared after this prompt.
The array size
is unknown, the value
is the pointer, and the sub
has to be assigned before the loop.
Here are the steps:
new
for the pointer.delete
for the dynamic array.While I'm trying to run the program, the error was:
error: ISO C++ forbids comparison between pointer and integer [-fpermissive]
for(int sub = 0; sub < size; size--)
--------------------------------------^
error: lvalue required as decrement operand
for (int sub = 0; sub > size; size--)
------------------------------------------------------^
Also, I am not sure what the keyword new
does.
#include <iostream>
using namespace std;
int main()
{
int size, array;
cout << "How many values would you like to enter? ";
cin >> array;
int value;
int *array = new int[size];
if (size > 0)
{
for (int sub = 0; sub < size; size++)
{
cout << "Enter value #" << size << ": ";
cin >> value;
}
while (size > 0);
}
else
{
while (size < 0)
{
cout << "Size must be positive." << endl;
cout << "How many values would you like to enter? ";
cin >> size;
}
}
cout << "Here are the values you entered in reverse order: \n";
for (int sub = size - 1; sub >= 0; size--)
{
cout << "Value #" << size << " :" << value << endl;
}
delete[] array;
return 0;
}
PS: I know size
is supposed to be unknown, but I've encountered another error saying
storage size of ‘size’ isn’t known
So, I add numbers to avoid that error.
Edit:So I changed the code thanks to @MikeCAT, but this error said terminate called after throwing an instance of 'std::bad_array_new_length what(): std::bad_array_new_length
. This was because I enter a negative number for the size
, which was supposed to happen for the if
statement. Also, I need the size
to start at 1 after the user enters how many values they want to enter, but the size
always starts at the number that was entered.
Upvotes: 0
Views: 116
Reputation: 75062
As the assignment says, you should
#include <iostream>
int main(void) {
// read a number (size of a dynamic array)
int numElements;
std::cin >> numElements;
// allocate a dynamic array
int *array = new int[numElements];
// read values for the dynamic array
for (int i = 0; i < numElements; i++) {
std::cin >> array[i];
}
// print the values in reversed order
for (int i = numElements - 1; i >= 0; i--) {
std::cout << array[i] << '\n';
}
// de-allocate the array
delete[] array;
// exit normally
return 0;
}
Error handling and non-essensial messages are omitted. Try adding them.
Upvotes: 1