Find the distinct elements in a given array in c
Answers
Answer:
You have not set the initial value of m to be equal to zero - it is undefined....
you also need to reset distinct to 1 for each element of the array you test. (in fact you don't need the variable distinct see below)
You also need to change the j loop - it should be
for(j=0; (j<m)&&(distinct==1); j++)
because j needs to loop through the array w
with these fixes it works.... (see below)
#include <stdio.h>
#include <stdlib.h>
int main()
{
int v[100], w[100], n, m=0, i, j, distinct=1;
printf("n= ");
scanf("%d", &n);
for(i=0; i<n; i++)
{
printf("v[%d]= ", i);
scanf("%d", &v[i]);
}
distinct=1;
for(i=0; i<n; i++)
{
for(j=0; (j<m)&&(distinct==1); j++)
if(v[i]==w[j])
distinct=0;
if(distinct==1)
{
w[m]=v[i];
m++;
}
}
printf("the distinct elements are: ");
for(i=0; i<m; i++)