Maximize area of a triangle given n points

1k Views Asked by At

The code runs perfectly when I arbitrarily pass arguments to the area function. But gives me a segmentation fault when I try to run the loops. Given n<100

Here's my code.

#include<stdio.h>
#include<math.h>
double area(int x,int y,int x1,int y1,int x2,int y2)
{       //Heron's formula
    double a,b,c,s;
    double abc;
    a=sqrt(((x-x1)*(x-x1))+((y-y1)*(y-y1)));
    b=sqrt(((x-x2)*(x-x2))+((y-y2)*(y-y2)));
    c=sqrt(((x2-x1)*(x2-x1))+((y2-y1)*(y2-y1)));
    s=(a+b+c)/2;
    abc=sqrt(s*(s-a)*(s-b)*(s-c));
    return(abc);
}
int main(void)
{   

    int n,i,j,k;
    double max=0,z=0;
    scanf("%d",&n);
    int x[100]={},y[100]={};
    for(i=0;i<n;i++)
    {
        scanf("%d %d",&x[i],&y[i]);
    }
    for(i=0;i<n;i++)
    {
        for(j=i+1;j<n;j++)
        {
            for(k=j+1;k<n;j++)
            {
                z=area(x[i],y[i],x[j],y[j],x[k],y[k]);
                printf("%lf\n",z);
                if(z>max)
                {
                    max=z;
                }
            }
        }
    }
    //printf("\n%lfoi\n",area(0,0,1,0,1,2));
    printf("%lf",max*2);

}
4

There are 4 best solutions below

1
On BEST ANSWER

The inner loop is incrementing j, it should probably increment k:

for(k=j+1;k<n;j++)
              ^
             oops!
3
On

there is an error index in inner loop: should be

for(k=j+1;k<n;k++)

instead of

for(k=j+1;k<n;j++)
0
On
for(k=j+1;k<n;j++)

I think you meant to increment k in this loop, not j.

0
On

You have to increase "k" not "j"

 for(k=j+1;k<n;k++)
        { }