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

For any given matrix find the path from the start to the end which gives the maximum sum. Traverse only right or down. Example: starting index is 15 (left top) and ending index is 10 (bottom right) 15 25 30 45 25 60 70 75 10 O/P:15->45->70->75->10 sum is 215

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