View Single Post
Old Mar 26th, 2008, 6:12 AM   #5
Sane
Programming Guru
 
Sane's Avatar
 
Join Date: Apr 2005
Posts: 1,799
Rep Power: 5 Sane will become famous soon enough
Re: duplicate numbers in arrays

There's a neat trick you can use to do this.

Use an array of zeroes. For each number they enter, set the n'th element to 1. After you're done, print out all elements that are 1.

This automatically stops itself from printing out duplicates, because setting an element to 1 twice still keeps it at 1.

Also, your validation of each number did not stop it from being added to the array. The assignment specifies to include duplicates as one of the 20 numbers, but do not count invalid numbers as one of the 20.

int main() {
    int idx = 0;
    int list[101] = {0}; // make an array of 101 zero's
    int n;
    int i;
    
    cout << "Enter 20 integers between 10 and 100: " << endl;
    
    for (i=0; i<20; i++) { // user inputs 20 numbers
       
        do {
            cout << "Enter number " << i+1 << ": ";
            cin >> n;
        } while (n < 10 || n > 100);  // input must be between 10 and 100

        list[n] = 1;  // this tells us the n'th number has been used

    }
    
    for ( int j = 10; j <= 100; j++ )
        if(list[j] == 1)
            cout << j << " ";  // index of all numbers that have a 1
        
    system("pause");
    return 0;
}

Note that this does not mantain the order the numbers were inputted.

If you need to mantain the order, you could keep your original code, and then use this method to output the array. As you're outputting it, set the element to 1. Then make sure you don't output a number if the list is set to 1 for that value.
Sane is offline   Reply With Quote