User Tools

Site Tools


cs509:arraynoduplicates

Array example from class, 3/6/13

/*
Write a program that uses an array to solve the following problem.
Read in 20 numbers, each of which is between 10 and 100, inclusive.
As each number is read, print it only if it is not a duplicate of a
number already read.
*/

#include <iostream>

using namespace std;

int main()
{
    const int asize = 20;

    int a[asize] = { 0 };

    // for loop to enter 20 values
    for ( int i = 0; i < asize; i++ ) {

        int currentvalue;

        cout << "\n Enter a value (between 10 and 100): ";
        cin >> currentvalue;

        bool duplicatefound = false;


        // inner for loop to search for each entered value in the array
        for ( int j = 0; j < asize; j++ ) {
            // If currentvalue I just entered is already in the array,
            if ( currentvalue == a[j] ) {
                //debug// cout << "\n duplicate found";
                duplicatefound = true;
                break; // found duplicate, so stop comparing
            }
        }


        // If no duplicate found, output the input number
        if ( duplicatefound == false )
            cout << currentvalue;


        a[i] = currentvalue; // wait until very end of for loop to insert currentvalue
    }

    return 0;

}
cs509/arraynoduplicates.txt · Last modified: 2013/03/07 07:49 by jchung

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki