Print Unique Elements From Array Using For Loop in CPP

    1. Home
    2. Tutorials
    3. CPP
    4. CPP Programs
    5. Array
    6. Program

    Source Code

    #include <iostream>

    using namespace std;

    int main(int argc, char** argv) {

    // array initialized with some duplicate values.
        int arr[10] = {45,54,16,33,45,12,80,69,54,45};
        int i,j; // counter variables.
        
        // print all values of array
        cout<<"Array having duplicate values"<<endl;
        for( i = 0 ; i < 10 ; i++ ) {
            cout<<arr[i]<<" ";
        }
        
        cout<<endl<<"Array After Skipping Duplicates"<<endl;
        // skipping duplicate values from array
        for( i = 0 ; i < 10 ; i++ ) {
            for( j = 0 ; j < i ; j++ ) {
                if( arr[i] == arr[j] ) {
                    break;
                }
            }
            if( i == j ) {
                cout<<arr[i]<<" ";
            }
        }
        return 0;
    }

    Output

    how to print unique elements from array in c++ using for loopWorking

    In this program first of all an array is initialized with some random data values. This array is intentionally initialized in such a way that we have put some duplicate values. Here we have 45 and 54 are duplicate values.

    This program will just skip these values from print. Before skipping these duplicate values we first print entire array having duplicate values. Then we use nested for loop that match each value from start of array and if it matches and the index is same as its first occurrence in array then value will print otherwise skipped.

    These entire source code is compleletly compiled and tested on Dev-C++ compiler.

    Comments
    Login to TRACK of Comments.