Breaking

Thursday 13 July 2017

No. of Distinct Elements in an unsorted array

No. of Distinct Elements in an unsorted array


Write a program to find the number of distinct elements in a unsorted array. [Do it without sorting the array]

Input Format:
Input consists of n+1 integers.
The first integer corresponds to n, the number of elements in the array.
The next n integers correspond to the elements in the array. Assume that the maximum value of n is 15.

Output Format:
Output consists of a single integer which corresponds to the number of distinct elements in the array.

Sample Input:
5
3
2
3
780
90

Sample Output:
4



Code:

#include<stdio.h>
int main()
{
int n,c=0,i,j,flag=0;
scanf ("%d",&n);
int arr[n];
for(i=0;i<n;i++)
scanf ("%d",&arr[i]);
for(i=0;i<n;i++)
{
    for(j=0;j<i;j++)
    {
       if(i!=j)
       {
           if(arr[i]==arr[j])
              { flag=1;
                  break;}

       }
    }
   if(flag==0)
       c++;
  else
   flag=0;
}
printf("%d",c);

return 0;
}  

No comments:

Post a Comment

Like