1-9 array finder help

Write a program that looks at a 1D array of 9 numbers and verifies that the array contains each of the
numbers 1-9 exactly once.
It should display a message "Valid Array!" if the array meets the requirement.
Otherwise, your program should let the user know what is wrong with the array.
(Does it contain a number out of the range? Is a number not found in the array? Is a number duplicated?) This is all i have for now and its missing some of the options listed please help





#include <iostream>

using namespace std;

int main ()
{
int number = 0;
int array[10]{};

while
(
cout << "Enter a number in the range 1-9 ( -1 to end ): " &&
cin >> number &&
number != -1
)
{
if(number > 0 && number < 10)
array[number]++;
else
cout << number << " wrong!\n";

}

for(int i = 1; i < 10; ++i)
cout << i << " occurred " << array[i] << " times.\n";

return 0;
}
not seeing the valid-array print statement for sure.

this is yet another application of the 'bucket sort'. There are other ways to do it, but this one is very simple. (It looks like you were headed in this direction, but you didnt check array[number] anywhere as validation, that is what you are missing).

looks like this:
unsigned long long int count[10] = 0;
...loop and read number, verify number in range.. etc as you have it
count[number]++; //you have it up to here already...
here you have a choice. if count[number] > 1, you have a duplicate and can complain right away:
if(count[number > 1) cout << "duplicate entered\n";

or you can wait until all 10 are input and validate whether it is correct or not. A very, very stubborn user could eventually overflow the count back to zero and break the code, but I think we can ignore that possibility here assuming 64 bit ull type.

the validation loop is simply

invalid = false;
for(i = 0; i < 10; i++)
if (count[number]!= 1) invalid = true;

Last edited on
Topic archived. No new replies allowed.