so my program is supposed to use one 5 sized array to store inputted integers. If it's a duplicated integer it would not be stored into the array.
The problem here is there would be 0's in my array indefinitely since i initialized the size to 5, there would always be 5 elements regardless if all 5 is being used or not. I need to output only the unique numbers how would i do so?
One thing i noticed was that without my unsigned int position; whenever i enter a duplicate integer it would skip the index;
e.g. array[0] = 10, array[1] = 10 // duplicate, array[2] = 20 // inputted 20, this should've been stored into array[1] but it doesn't. So i had the position to only increment whenever it's not a duplicate to make sure it's not skipping over the index when a duplicate is entered.
So the problem is if say my input was 10 10 20 30 40, my outputted display would be 10 20 30 40 0 because the last index is not used since the 2nd Int 10 input was ignored and not stored into the array but the counter would still increment for the outer loop to prompt the user to enter the next #; instead i want it to be just 10 20 30 40 and not output the 0.
And was there anything i could've done or do a different approach to get my result?
Code:
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
|
#include <iostream>
#include <iomanip>
#include <array>
using namespace std;
const unsigned int MIN_VALUE = 10;
const unsigned int MAX_VALUE = 100;
const size_t arraySize = 5;
array <int, arraySize> numberArray = {};
template<size_t size>
bool isDuplicate(array<int, size> array, int value)
{
for (unsigned int i = 0; i < array.size(); i++)
{
if (value == array[i])
{
return true;
}
}
return false;
}
int main()
{
unsigned int input;
unsigned int position = 0;
for (unsigned int i = 0; i < arraySize; i++)
{
cout << "Enter # " << (i + 1) << " : ";
cin >> input;
if (input < MIN_VALUE || input > MAX_VALUE)
{
cout << "The number entered is not in valid range of 10 to 100" << endl;
--i;
}
else if (!isDuplicate(numberArray, input))
{
numberArray[position] = input;
position++;
cout << "The number: " << input << " is unique\n" << endl;
}
}
}
|
Thanks!