In: Computer Science
C coding
• Implement, using structures and functions as appropriate, a
program which requires you to enter a number of points in 3
dimensions. The points will have a name (one alphanumeric
character) and three coordinates x, y, and z. Find and implement a
suitable way to stop the input loop. The program, through an
appropriate distance function, should identify the two points which
are the furthest apart. Another function should calculate the
centre of gravity of the point cloud (i.e., the average of each
coordinate for all points entered)
• The output should show a list of the points entered, then name and list the two that are furthest apart, and finally list the centre of gravity. Note: you should use pointers when passing structs to functions to get full marks.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct Point{
int x,y,z;
char name;
struct Point *next;
}Point;
Point *head=NULL;
int x_sum=0;
int y_sum=0;
int z_sum=0;
int count=0;
Point* insert(Point *head,Point *new_val)
{
count++;
x_sum+=new_val->x;
y_sum+=new_val->y;
z_sum+=new_val->z;
if(head==NULL)
{
head=new_val;
}
else
{
new_val->next = head;
head = new_val;
}
return head;
}
double getDistance(Point *p1,Point *p2)
{
int d1=p1->x-p2->x;
if(d1<0)d1=d1*-1;
int d2=p1->y-p2->y;
if(d2<0)d2=d2*-1;
int d3=p1->z-p2->z;
if(d3<0)d3=d3*-1;
double distance=d1*d1+d2*d2+d3*d3;
distance=sqrt(distance);
return distance;
}
int main()
{
int x_temp,y_temp,z_temp;
char name_temp;
int choice=0;
do{
printf("Enter point (X Y Z name)\n");
scanf("%d %d %d
%c",&x_temp,&y_temp,&z_temp,&name_temp);
Point *temp=(Point *)malloc(sizeof(Point));
temp->x=x_temp;
temp->y=y_temp;
temp->z=z_temp;
temp->next=NULL;
temp->name=name_temp;
head=insert(head,temp);
printf("Press 1 to continue : \n");
scanf("%d",&choice);
}while(choice==1);
printf("POINTS :\n");
for(Point *loop=head;loop!=NULL;loop=loop->next)
{
printf("Point %c : %d %d %d
\n",loop->name,loop->x,loop->y,loop->z);
}
double max=0;
Point *p1,*p2;
for(Point *temp1=head;temp1!=NULL;temp1=temp1->next)
{
for(Point *temp2=temp1;temp2!=NULL;temp2=temp2->next)
{
double distance=getDistance(temp1,temp2);
if(distance>max)
{
max=distance;
p1=temp1;
p2=temp2;
}
}
}
//printf("Center of Gravity : %f %f
%f\n",((double)x_sum)/count,((double)y_sum)/count,((double)z_sum)/count);
printf("Center of Gravity : %d %d
%d\n",x_sum/count,y_sum/count,z_sum/count);
printf("MAXIMUM DISTANT POINTS %c :%d %d %d and %c :%d %d %d at distance %f\n",p1->name,p1->x,p1->y,p1->z,p2->name,p2->x,p2->y,p2->z,max);
}
OUTPUT: