In: Computer Science
C Language
Let us define a Point type to store two-dimensional coordinates (x, y)! Write the following functions operating on this data type:
In the main, define two points, and test all these functions. When all tests are passed, solve the following task by utilizing the structure and functions defined above:
A farmer wants to surround his land with a wire fence. Write a C program to compute how much fence is required! The program asks the farmer to enter the coordinates of the corner points of the fence, calculates the distances, and sums them up. Repeat these steps as long as the new coordinates are not equal to the first one (hence, till we return to the starting point).
It is recommended to store the starting point in a separate variable. After that, two more point variables are needed to calculate the length of a fence segment: one of them stores the current point, and the other the previous one.
Complete code in C:-
#include <stdio.h>
#include <math.h>
// Data structure that stores points' 'x' coordinate, 'y'
coordinate.
typedef struct node {
float x, y;
}Point;
// This function is used to square a 'double' type number
double sqr(double x) {
return x*x;
}
// Function used to take coordinates of points as input from
user
Point read() {
double x, y;
printf("Enter 'X' coordinate : ");
scanf("%lf", &x);
printf("Enter 'Y' coordinate : ");
scanf("%lf", &y);
Point point = {x, y};
return point;
}
// Checks if two points are equal or not?
int equal(Point first, Point second) {
return (first.x == second.x && first.y ==
second.y);
}
// Returns distance between two points, using pythagorean
formula.
double dist(Point first, Point second) {
double temp = (sqr(first.x - second.x) + sqr(first.y -
second.y));
double len = sqrt(temp);
return len;
}
// Main function
int main(void) {
// This variable will store the length of
fence.
double requiredFence = 0;
// Taking first point input
Point first = read();
// Taking secdon point input.
Point second, current = read();
// Calculating distance between first and current
point.
requiredFence += dist(first, current);
// Run this while loop until reads first point
again from user
while(equal(first, current) == 0) {
second = current;
current = read();
requiredFence += dist(second,
current);
}
printf("\nTotal fence required : %lf\n",
requiredFence);
return 0;
}
Screenshot of output:-