A point is defined by its real coordinates (X, Y).

The purpose of this program is to allow the user to enter N distinct points, calculates and prints the smallest distance between any two points of the sequence. Two arrays should be used to store the points’ coordinates: X[N] (for points’ abscissa) and Y[N] (for points’ ordinate) as shown in the example bellow.

Example: if N = 4, and the 4 distinct points are (1,2); (3, -2); (11, 2); (9,3), then the two arrays X and Y will be as following:

$$\begin{array}{c | c | c| c| c| }\hline  X: & 1 & 3 & 11 & 9 \\ \hline  \end{array}$$

$$\begin{array}{c | c | c| c| c| }\hline  Y: & 2&-2&2 &3 \\ \hline \end{array}$$

  • Write the function $$\texttt{int FindInRange (float A [], int M, float v)}$$, that checks if the value v appears in the first M elements of the array A.
  • Write the function $$\texttt{void ReadDistinctPoints (float X [], float Y [], int N)}$$, that prompts to enter the coordinates X and Y of N distinct points: Any new entered point that has been already entered in the sequence of points should not be considered (Hint: use the function FindInRange).
  • Write a main program that asks the user to enter N distinct points (by storing their coordinates in two arrays X and Y), calculates and prints the smallest distance between two points of the sequence of points.

Note:

  • the distance between two points $$A(x_1,y_1)$$ and $$B(x_2,y_2)$$ is equal to $$d=\sqrt{(x_2-x_1)^2+(y_2-y_1)^2}$$
  • The use of the library math.h is allowed.

Difficulty level
This exercise is mostly suitable for students
#include <stdio.h>
#include <math.h>
#define S 100
 
 
int FindInRange(float A [], int M, float v)
{
    int i;
    for(i=0;i<M;i++)
        if(A[i]==v)
            return 1;
    return 0;
}


void ReadDistinctPoints (float X [], float Y [], int N)
{
    int i;
    for(i=0; i<N;i++)
    {
        do{
            printf("Enter x for point %d: ", i+1);
            scanf("%f",&X[i]);
            printf("Enter y for point %d: ", i+1);
            scanf("%f",&Y[i]);  
        }while(FindInRange(X,i-1,X[i]) && FindInRange(Y,i-1,Y[i]));
    }
}

int main()
{
    float X[S], Y[S] ,dmax,d;
    int i, j, size;

    
    do{
        printf("Enter the number of points: ");
        scanf("%d", &size);
    }while(size<=0 || size > S);

    ReadDistinctPoints(X, Y, size);
    
    dmax=0;
    for(i=0; i<size-1;i++)
        for(j=i+1;j<size;j++)
        {
            d=sqrt(pow(X[j]-X[i],2)+pow(Y[j]-Y[i],2));
            if(d>dmax)
                dmax=d;
        }
    printf("Max distance = %f\n",dmax);
    return 0;
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Graph Edge Property