Write a structure declaration for a straight line and a function which, given the coordinates of a point on the line and its gradient, displays the equation of the line.

equation of a straight-line: y = mx + c

Source Code

Brief explanation is provided after the source code.


struct point {
    int x;
    int y;

typedef struct line {
    struct point pt;
    int m;
    int c; // intercept
} Line;

int main(int argc, char ** argv) {
    equation(2, 3, 1);
    equation(1, 3, 1);
    return 0;

void equation(int x, int y, int m) {
    Line line;
    line.m = m;
    line.pt.x = x;
    line.pt.y = y;
    line.c = line.pt.y - m*line.pt.x;

    printf("Equation of the line: y = %dx + %d\n", line.m, line.c);

When you compile and execute the above program it produces the following result on Linux:

Equation of the line: y = 1x + 1
Equation of the line: y = 1x + 2

Brief Explanation

  • A structure in C is a collection of one or more variables, possibly of different types, grouped together under a single name for convenient handling.
  • The basic object is a point with an x and y coordinate. The two components is placed in a structure point.
  • The keyword struct introduces a structure declaration, which is a list of declarations enclosed in braces.
  • An optimal name called a structure tag may follow the word struct (as with point here). The tag names this kind of structure, and can be used subsequently as a shorthand for the part of the declaration in braces.
  • The variables named in the structure are called members.
  • A structure declaration that is not followed by a list of variables reserves no storage; it merely describes a template or shape of a structure.
  • The line structure contains the point structure and the variables m for gradient and c for intercept.
  • Using typedef, Line is created as a synonym for the structure line. Line is then use in the equation function to define a variable line of type structure. i.e Line line
  • The equation function takes as input three parameters (x, y, m) and display the equation of the straight line.

Add comment

Security code