C program to find the sum of unique elements in an array

Logic:

1.sort the elements
2.Then read the elements one by one
                  i) If the current element and the next element are not the same add the current element to the sum and then finally print the sum at the end.

Program:

#include<iostream>
using namespace std;
int main()
{
    int n;
    cin>>n;
    int i;
    int a[n];
    for(i=0;i<n;i++)
    {
        cin>>a[i];
    }
    //sort the std::array<T, N> ;
    
    int j;
    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
        {
            if(a[i]<a[j])
            {
                int temp=a[i];
                a[i]=a[j];
                a[j]=temp;
            }
        }
    }
    int sum=0;
    for(i=0;i<n;i++)
    {
        if(a[i]!=a[i+1])
        {
            sum=sum+a[i];
        }
    }
    cout<<sum;
}

Output:

5                                                                                                                                              
2 2 3 3 5                                                                                                                                      
10                                                                                                                                             

10                                                                                                                                             
22 33 3 4 5 22 33 4 5 10                                                                                                                       
77                                                                                                                                             

Comments

Popular posts from this blog

C program to print the following Pattern

c++ program to print string along the diagonals of the matrix.

Kollywood Game