You've managed to use code tags but have somehow lost your indentation anyway! :-)
If you want to learn proper C++, then VLAs (variable-length arrays) are not legal. They were introduced into C in C99 and made optional in C11, so even the C people think they're a bad idea.
|
int createdArray[range]; // not standard C++
|
Instead we say this:
1 2 3 4
|
int* createdArray = new int[range];
//and you need to remember to delete it when you are done with it:
delete[] createdArray;
|
However, it's even better to use a vector:
|
vector<int> createdArray;
|
With a vector the memory allocation/deallocation is handled automatically and you can use the push_back() member function to append values to it.
Here you have another use of VLAs, but even if they were legal, this is incorrect:
1 2 3 4
|
int range1 = 0;
int range2 = 0;
int evenArray[range1];
int oddArray[range2];
|
That would create two arrays of 0 size. They won't automatically get bigger just because you increment range1 or range2. Also, in your algorithm, you are using j to index those arrays where you should be using range1 and range2 (i.e., the current size).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
#include <iostream>
using namespace std;
int main()
{
int range;
while (true)
{
cout << "Please enter a number between 1 to 5: ";
cin >> range;
if (range >= 1 && range <= 5)
break;
cout << "That value is not in range.\n";
}
int* createdArray = new int[range];
for (int i = 0; i < range; ++i)
{
int score;
while (true)
{
cout << "Enter your " << (i + 1) << " score (1-100): ";
cin >> score;
if (score >= 1 && score <= 100)
break;
}
createdArray[i] = score;
}
cout << "\nArray the way user entered: ";
for (int i = 0; i < range; ++i)
cout << createdArray[i] << ' ';
cout << "\nArray in reverse order: ";
for (int i = range; i-- > 0; )
cout << createdArray[i] << ' ';
cout << "\n\nFinding even scores stored in array.\n";
int range1 = 0, range2 = 0;
int* evenArray = new int[range]; // making them size of createdArray
int* oddArray = new int[range]; // which will be big enough.
for (int i = 0; i < range; ++i)
if (createdArray[i] % 2 == 0)
evenArray[range1++] = createdArray[i];
else
oddArray[range2++] = createdArray[i];
cout << "Even array: ";
for (int i = 0; i < range1; ++i)
cout << evenArray[i] << ' ';
cout << '\n';
delete[] oddArray;
delete[] evenArray;
delete[] createdArray;
}
|